skip to Main Content

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


  1. 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:

    // Get all user_item elements
    let userItems = document.querySelectorAll('.user_list .user_item');
    
    let usersArray = [];
    
    userItems.forEach(item => {
      let onclickString = item.getAttribute('onclick');
      
      // Extracting the parameters from the onclick string
      let params = onclickString.match(/dropUser((d+),'(.*?)','(.*?)');/);
      
      if(params) {
        let userObj = {
          id: parseInt(params[1]),
          name: params[2],
          gender: params[3]
        };
        usersArray.push(userObj);
      }
    });
    
    console.log(usersArray);
    

    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:

    1. 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.

    2. Extract onclick Attribute: The item.getAttribute(‘onclick’) will extract the string value of the onclick attribute of the user_item div.

    3. Parse the onclick String: The Regular Expression match(/dropUser((d+),'(.?)’,'(.?)’);/) is used to extract the parameters from the onclick string.

    4. Create User Object: Once the parameters are extracted, an object userObj is created with those parameters and then it is pushed to the usersArray.

    5. 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.

    Login or Signup to reply.
  2. No need for jQuery to do this. It’s just some simple string parsing to extract this data.

    const userItems = document.querySelectorAll('.user_list .user_item');
    const dropUsersData = [];
    
    for(userEl of userItems){
      //get the string content of the `onclick` attribute
      const onClickStr = userEl.getAttribute('onclick');
      //remove the function name, wrapping parens, and ending semicolon
      const onClickContent = onClickStr.replace('dropUser(','').replace(');','');
      //Take the params and use the commas to separate each one into an array item
      //Then remove the quote marks around any string literals
      const onClickParams = onClickContent.split(',').map(s=>s.replace(/'/g,''));
      
      //Add the found parameters to the array
      // turning the ID into a real number and
      // saving the actual element reference (if needed)
      dropUsersData.push({
        element: userEl,
        id: parseInt(onClickParams[0], 10),
        name: onClickParams[1],
        gender: onClickParams[2]
      })
    }
    
    console.log(dropUsersData);
    <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>
    Login or Signup to reply.
  3. 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.

    var arr=[];
    $('.user_item').each(function(){
        var onClickDataArr = $(this).attr('onclick').match(/(([^)]+))/)[1].split(',');
        userData = {
          id: parseInt(onClickDataArr[0]),
          name: onClickDataArr[1].replace(/'/g, ""),
          gender: onClickDataArr[2].replace(/'/g, "")
        };
        arr.push(userData);
    });
    
    console.log(arr);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search