I have an html web page containing the following tags:
<div class="user_list">
<div onclick="dropUser(2483071,'Jack','m');" class="user_item">
<div class="avatar"><img " src="..."> </div>
</div>
<div onclick="dropUser(2483075,'Sara','f');" class="user_item">
<div class="avatar"><img " src="..."> </div>
</div>
....
</div>
I want to make an array of objects containing dropUser parameters in onClick event as shown bellow:
array = [
{id: 2483071, name: 'Jack' , gender: 'm'},
{id: 2483075, name: 'Sara' , gender: 'f'},
...
]
how may i get that.In my way I want to find the onClick props then map each item to the array objects. I can get the elements by the following method but I dont know how to get the onClick prop then the dropUser parameters.:
s.push($(".user_list" ).find( ".user_item" ));
for(let i = 0; i<s.length-1; i++){
console.log($(s[i]);
}
3
Answers
You can achieve this by creating a function to extract the onclick attribute and then parse the parameters from the string. After extracting the parameters, you can then map them to an object and push them to the array.
Here’s a simple example of how to achieve this using plain JavaScript:
This code will create the usersArray array with objects containing the id, name, and gender for each user.
Here’s a step-by-step explanation of the process:
Get User Items: The document.querySelectorAll(‘.user_list .user_item’) will get all the elements with the class user_item inside the parent with class user_list.
Extract onclick Attribute: The item.getAttribute(‘onclick’) will extract the string value of the onclick attribute of the user_item div.
Parse the onclick String: The Regular Expression match(/dropUser((d+),'(.?)’,'(.?)’);/) is used to extract the parameters from the onclick string.
Create User Object: Once the parameters are extracted, an object userObj is created with those parameters and then it is pushed to the usersArray.
Result: The usersArray will hold the objects representing the users with their id, name, and gender properties extracted from the onclick attribute.
Note
It’s crucial to note that using getAttribute(‘onclick’) and parsing the function call is somewhat fragile and might not be the best practice. If you have control over the HTML, it would be more robust to store this data in data- attributes or to generate this array on the server side, depending on your application’s architecture.
No need for jQuery to do this. It’s just some simple string parsing to extract this data.
Using jQuery you can achieve it easily:
a) Get the
onclick
attribute value.b) get data between the
()
and then split it with,
to make it array.c) create an object and assign correspoing values to different indexes.make sure quotes get removed befor assignment.
d) push this object to array created initially.