I have this html string in a javascript variable and want to get the id value.
I converted it to pure html and than I tried to get the id value of the div.
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.find('.multiid').attr("id");
The result should be var multiid = 3041
but it does not work.
I have this html string in a javascript variable and want to get the id value.
I converted it to pure html and than I tried to get the id value of the div.
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.find('.multiid').attr("id");
The result should be var multiid = 3041
but it does not work.
-
8
use
multiid = multiidhtml.attr("id");
– Nikos M. Commented Dec 21, 2018 at 10:45 -
1
You don't need to do the find as the
.multiid
is the top level element in your jquery object – Pete Commented Dec 21, 2018 at 10:46
4 Answers
Reset to default 4The attribute id you are looking for is in the jQuery object itself. But find(.multiid)
looks for elements with class multiid inside the object (as nested elements) which does not realy exists and the attr()
returns undefined.
Try multiidhtml.attr("id");
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.attr("id");
console.log(multiid);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Consider the following example where you can use find()
meaningful:
var rowData = "<div id='3041' style='height:100%;' >test <p class='multiid' id='myParagraph'>Nested P</p></div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.find('.multiid').attr("id");
console.log(multiid);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
.find()
searches the descendants of the element, it won't match the element itself. You should wrap the HTML in another DIV so it won't be the top-level element.
var multidhtml = $("<div>", {html: rowData});
var multiid = multidhtml.find(".multiid").attr("id");
This is only necessary if .multiid
might not be the top-level element. If it's always the top, use the simpler solution in the other answer.
.find() searches the descendants of the element, it won't match the element itself. SO use .closest() so that it searches from the root of selector DOM
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.closest('.multiid').attr("id");
if you're sure that id attribute exists in the selected DOM you can directly find like this
multiid = multiidhtml.attr("id");
var rowData = "<div id='3041' style='height:100%;' >test <p class='multiid' id='myParagraph'>Nested P</p></div>";
var multidhtml = $("<div>", {html: rowData});
var multiid = multidhtml.find(".multiid").attr("id");