0

I have a ul menu from which I want to retrieve certain information:

<ul id="form_builder_sortable" class="sortable rightDiv session1">
    <li class="draggable ui-state-highlight item id10" name="Maths">Maths<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
</ul>

I have a function in javascript:

function getSessionDatas()
{
    var sessions = [];
    $('.rightDiv').each(function(index)
    {
        var session = $.trim($(this).text().slice(0, -1)).split("×");
        var sessionData = [];
        for (var i = 0; i < session.length; i++)
        {
            var s = {
                subjectOrder: i,
                subjectID: subs[session[i]]
            };
            sessionData.push(s);
        }
        var ses = {
            sessionNo: index,
            sessionData: sessionData
        };
        sessions.push(ses);
    });
}

Here:

var s = {subjectOrder:i, subjectID:<get id here>};

I want to assign the subject id according to the class of the <li> item, in this case in the class there is an id10. How can I assign the subjectID to 10 in this case?

2
  • Will there be multiple li in each rightDiv? Which id value will be assigned in that case? Commented Jan 19, 2018 at 8:51
  • @gurvinder372 yes, there will be multiple li, and the id value will be different. It is going to be the id of the subject in the database Commented Jan 19, 2018 at 8:52

3 Answers 3

7

I would suggest you to use data-* prefix custom attribute which can be retrieved using .data(key) method.

$('.rightDiv li').each(function(index) {
  var id = $(this).data('id')
  console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="form_builder_sortable" class="sortable rightDiv session1" >
  <li data-id="10" class="draggable ui-state-highlight item" name="Maths">Maths<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
  <li data-id="11" class="draggable ui-state-highlight item" name="Maths">English<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
</ul>

for those not using jQuery, same can be fetched using HTMLElement.dataset property

var id = this.dataset.id;
Sign up to request clarification or add additional context in comments.

1 Comment

@DaniM Will each li have a different id value? If so, add the data-id attribute to the li instead of the ul and this will work (in principle - just a minor change).
2

While this isn't a particularly good approach, it is possible to retrieve a specific class-name from an element's classes, so long as you can predict a particular pattern. In this case, for example, that the required class-name begins with the string of id:

// elem:   a single node reference, the element from which
//         you want to retrieve a specific class-name;
// prefix: String, the string with which the required
//         class-name(s) begins.
function retrieveClassByPrefix(elem, prefix) {

  // either elem, or prefix, are undefined or otherwise
  // falsey we quit here:
  if (!elem || !prefix) {
    return false;
  }

  // otherwise we convert the classList of the element into
  // an Array, using Array.from() on the result returned from
  // elem.classList, and then use Array.prototype.filter()
  // to filter the Array:
  return allClasses = Array.from(elem.classList).filter(

    // currentClass - using an Arrow function - is a reference
    // to the current class-name of the Array of class-names over
    // which we're iterating; if the currentClass String begins
    // with the supplied String ('prefix') then that class-name
    // is retained in the Array:
    currentClass => currentClass.startsWith(prefix)
  );

}

let idClassName = retrieveClassByPrefix(
  document.querySelector('#form_builder_sortable > li:first-child'), 'id'
);

3 Comments

Thank you David for the time you put to this one. I accepted an answer above as it is easier for me to understand, thanks again!
I think it should be document.querySelector('#form_builder_sortable > li:first-child'), 'id' (minor syntax error)
@Satpal: you're absolutely right (of course); thanks, that's what comes of answering via phone... >.<
0

You can get the classes of your li element, and find which one match with idXX

var regexId = /id([0-9]+)/gi
$('.rightDiv').each(function( index ) {
 //do some stuff
  $(this).find("li").each(function(){
      var classes = $(this).classes.split(/\s+/); // get the classes in an array
      for(var c in classes){
        c = classes[c]; //one classe
        var regexExec = regexId.exec(c);
        if(regexExec  && regexExec.length > 1){
                var id = regexExec[1];
               //do your stuff with the id 
               break;
           }
      }
   }
}

1 Comment

Thank you for your effort, I had to accept another answer, but this is really good as well :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.