Get element's html tag content - javascript

Is it possible to get a node's top-level tag html via the dom api? To be clear, if I have
<div data-x="a">
<span>Hello</span>
</div>
I want to just get back <div data-x="a">
Is a crude string matching on outerHTML the best I can do, or is there a fast and direct way to achieve what I want?

If you clone the node, the innerHTML property will be empty.
For your example, a shallow clone is appropriate (pass false or don't pass anything).
// get the div element
var element = document.querySelectorAll('div')[0];
// view the outerHTML of the element
console.log('original outerHTML', element.outerHTML);
// clone the element
var clone = element.cloneNode();
// view the outerHTML of the clone
console.log('outerHTML of clone', clone.outerHTML); // has what you want
<div data-x="a">
<span>Hello</span>
</div>
.cloneNode() on MDN

You can use the outerHTML to get all of it, and the innerHTML to get the stuff just inside. Then do a string replace on the outerHTML, replacing the innerHTML with an empty string, and doing the same for the end tag.

Related

Append values to a specific element in a string with Jquery

I have an element in local storage with multiple elements, for simplicity, I will make the element:
<div id="outer">
<ul id="inner">
<li id="item">
</li>
</ul>
</div>
The element is saved as a string and I want to manipulate the contents.
Like such:
let local_storage_element = localStorage.getItem("val")
$(local_storage_element+':last-child').append("<p>something</p>")
No matter what selector I add after local_storage_element it will always append the value to the string not to the selected element(:last-child in this case)
does anyone know how to append to a specific element within the string??
Although you have written jquery in the title there is a javascript tag added also so I thought why not provide an answer that justifies your needs and helps you accomplish the task in the same way you want.
The
DocumentFragment interface represents a minimal document object that has no parent. It
is used as a lightweight version of Document that stores a segment of
a document structure comprised of nodes just like a standard document.
The key difference is that because the document fragment isn't part of
the active document tree structure, changes made to the fragment don't
affect the document, cause reflow, or incur any performance impact
that can occur when changes are made.
So how to do it as the DocumentFragment still appends node with it and not string, we will create a temp element and add the HTML from the localStorage using innerHtml and then append the firstChild of that temp node i.e our actual string which is now treated as a node, to the document fragment and then search and appends HTML to it, we will use our temp element to add HTML every time see below.
I will append a new child div to the element #outer in the string given above in the post here is the working FIDDLE as SO does not support localStorage you can see it working there open the console to view the resulting HTML with the new child added and below is the code
$(document).ready(function () {
if (localStorage.getItem('html') === null) {
localStorage.setItem('html', '<div id="outer"><ul id="inner"><li id="item"></i></ul></div>');
}
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = localStorage.getItem('html');
frag.appendChild(temp.firstChild);
temp.innerHTML = '<div class="new-child"></div>'
frag.querySelector("#outer").appendChild(temp.firstChild);
console.log(frag.querySelector("#outer"));
localStorage.removeItem('html');
});
You can't use string as selector. If you want transform string to html then you should put it in some element as innerHTML. So try create some hidden div and insert your string as HTML to it. Something like this
var your_string = '<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>';
document.querySelector('.hidden').innerHTML = your_string;
document.querySelector('ul li:last-child').innerHTML = 'your content';
document.querySelector('.result').appendChild(document.querySelector('ul'));
Example
The problem may arise when you get '<div id="outer">' from localStorage to use it as a selector since it only accepts "#outer" to be a selector. If you want to add an element to be the last child of parent's element, you could use after() instead of append().
$(document).ready(() => {
if ($("#charl").children().length === 0)
{
// if using after with no element inside ul then it will be inserted after il
$("#charl").html("<li>foo</li>")
}
else {
$("#charl li").after("<li>bar</li>")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="charl">
<li>Foo</li>
</ul>

get the style of a cached dom element using .find()

i cached a <div> in an object, and i want to use .find() method to get its style property without touching the DOM
lets say:
<body>
<div id="one" style="visibility:visible;">
</div>
</body>
<script>
var cache = {
cacheBody: $("body").find("div#one")
}
//i want to do this
chach.cacheBody.find("style") //or chach.cacheBody.find("visibilty")
</script>
the importent thing is that, i dont want to use jquery on DOM for this.
but on the cached object
var cache = {
cacheBody: $("div#one")
}
//i want to do this
var style= cache.cacheBody.attr("style"); //or chach.cacheBody.find("visibilty")
console.log(style);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" style="visibility:visible;">
</div>
I believe your use of .find() here is incorrect. It is used to traverse the DOM and "find" nodes that match the parameter given.
What you may be after is .attr(). If you want to get the style specific to that DOM Node which was given inline. Otherwise if you want the entire CSSStyleDeclaration object, you can use:
$('div#one')[0].style // instead of $('div#one').attr('style')
To get a complete object of all applied (and not applied) styles to the Node.
This is not as browser compatible as the rest of the code as it does not make use of jQuery for retrieving the actual object.

Get content of a div before and after id (or class) with native Javascript

I'm trying (in native Javascript, so without jQuery or anything) to get content before and after occurence of a div.
HTML:
<div id="thisIsWhatIWant">
<span>foo</span>
<div id="helloWorld">hello world</div>
<p>bar</p>
</div>
So I want to get <span>foo</span> and <p>bar</p> in separate vars.
JS:
var beforeElement_helloWorld = ...do something to get <span>foo</span>...
var afterElement_helloWorld = ...do something to get <p>bar</p>...
note:
There may be many more divs, spans etc in the HTML example.
You need this:
var previous = document.getElementById("helloWorld").previousElementSibling;
var next = document.getElementById("helloWorld").nextElementSibling;
Also read this,
The difference between previousSibling and previousElementSibling, is that previousSibling returns the previous sibling node as an element node, a text node or a comment node, while previousElementSibling returns the previous sibling node as an element node (ignores text and comment nodes).

Get html of the outer element

I have element as follows
<div id="features" class="feature" data-id="1">
<a href="http://www.google.com></a>
<img src="/sample.jpg">
<p> Sample content </p>
</div>
I want to get outer html of the div without inner children as follows
<div id="features" class="feature" data-id="1"></div>
How do i do it without jquery?
The simplest way without actually affecting the page (i.e. actually removing all of the children) is to clone the DOM node:
var featuresEl = document.getElementById('features');
var clonedEl = featuresEl.cloneNode(false); //False to not clone children
console.log(clonedEl.outerHTML); //Returns what you wanted, without inners
Demo (see console)
Probably a nicer way.. but you could do this
var node = features.cloneNode(); // clone your element
node.innerHTML = ''; // empty the cloned version
console.log(node.outerHTML); // ouput
http://jsfiddle.net/gtzzrfnL/
To get only the element without any children try to get the Whole html and remove all the children:
$('#features')[0].outerHTML.replace( $('#features')[0].innerHTML,'')
bye

Parent innerHTML and child nodes

I want to ask if I want to remove an HTML element's children but I don't necessarily want to loop through them, would setting the parent's ìnnerHTML to null or an empty string remove the children from memory, not just from the visual part of the document?
Yes, it will completely remove children.
For example, you have:
<div id="a_div">
<input type='button'><br>
<img src='image.png'>
</div>
Then
document.getElementById("a_div").innerHTML="<input type='button'><br><img src='image.png'>";
So if you set innerHTML to "" (document.getElementById("a_div").innerHTML="";), then a_div will be
<div id="a_div">
</div>
If you are using jQuery then empty() function used on the parent element will remove the elements from the DOM.

Categories