简体   繁体   中英

Is it possible to get the string inside the enclosing '<' and '>' of a tag using jquery or plain javascript?

If my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

 <div id="foo" class="something" style="width:80%; display:inline-block"> Hello! <div id="bar" class="something_else"> How are you?Hope you are doing well! </div> </div> 

Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want

div id="foo" class="something" style="width:80%; display:inline-block"

Is it possible to get this without using regex/string matching?

You can get the outerHTML and then parse the part you want:

 console.log( document.getElementById('foo').outerHTML.match(/<([^>]+)>/)[1] ); 
 <div id="foo" class="something" style="width:80%; display:inline-block"> Hello! <div id="bar" class="something_else"> How are you?Hope you are doing well! </div> </div> 

Using javascript element.nodeName and element.attributes to form a string:

 var foo = document.getElementById('foo'); console.log(crazyString(foo)); function crazyString(el) { var a = [el.nodeName]; var atts = el.attributes; for (var i=0; i < atts.length; i++) { a.push(atts[i].name + '="' + atts[i].value + '"'); } return a.join(" "); } 
 <div id="foo" class="something" style="width:80%; display:inline-block"> Hello! <div id="bar" class="something_else"> How are you?Hope you are doing well! </div> </div> 

You can try something like this,

 var element = document.getElementById("foo"); var tag = element.tagName; $.each(element.attributes, function() { tag += " "+ this.name + '"'+ this.value+ '"'; }); alert(tag); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="foo" class="something" style="width:80%; display:inline-block"> Hello! <div id="bar" class="something_else"> How are you?Hope you are doing well! </div> </div> 

Another version using Array#reduce

 let el = document.getElementById('foo'); let res = [].slice.call(el.attributes).reduce((a, c) => { return a.concat(c.name + '="' + c.value + '"'); }, [el.tagName.toLowerCase()]).join(' '); console.log(res) 
 <div id="foo" class="something" style="width:80%; display:inline-block"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM