-1

Is searching possible in html tags on the behalf of ID? for example to find div tag having id="abc".

I can use document.getElementByID("abc"). But i need parent div + its inner HTML in return of searching. i.e if this div has childs

bkashaf
  • 152
  • 2
  • 12

3 Answers3

2

Try this :-

<script >
function showHTML(){



   var vinner=document.getElementByID("abc").innerHTML;
   var totalinner="<div >"+vinner+"</div>";
   alert(totalinner);

}
</script>

HTML part:-

<body onload="showHTML();">

<div id="abc">
    Hello inside abc
    <div> 
            Inner div inside abc tag.
    </div>
</div>
</body>

Its working fine. You can get Attributes here.

Community
  • 1
  • 1
JDGuide
  • 6,239
  • 12
  • 46
  • 64
1

It's hard to understand what you want to achieve:

document.getElementById("abc").parentNode.innerHTML; 
//will return <div id="abc"> and other items from parrent

document.getElementById("abc").getAttribute("name");
//will atribute of <div id="abc">

if (document.getElementById("abc").hasChildNodes()) {
    // It has at least one
}

Using jQuery is much simplier, you could do that:

$("#abc").attr('id') //retunrs id
$("#abc").attr('class') //returns classes
//or other manipulations
Igor S.
  • 3,332
  • 1
  • 25
  • 33
1

One way to do this is to use outerHTML, which:

gets the serialized HTML fragment describing the element including its descendants.

Given the following HTML:

<div id="abc" data-attr="A custom data-* attribute">Some text in the div.</div>

The following JavaScript will log, in the console, the HTML of the element of id equal to abc:

var htmlString = document.getElementById('abc').outerHTML;
console.log(htmlString);

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410