Get html of the outer element - javascript

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

Related

Is there a way to get the exact indexOf an element in a big html string

I am working on an app with vue.js and quill.js in which I am creating some documents.
The content of a document is stored in document.content which is one giant string with a bunch of html tags in it coming straight from quill.js.
When previewing the document I'm rendering the big html string inside a div with v-html attribute like this:
<div v-html="document.content"></div>
i.e.
document.content = "<p>Hello</p><p>World</p><p>Hello World</p><p>Hello</p>"
It's rendereded as (you get the idea):
<div data-v-4ee08204>
<p>Hello</p>
<p>World</p>
<p>Hello World</p>
<p>Hello</p>
</div>
The question is:
When clicking somewhere inside the div is there a way to get the exact index of the character/word/element I've clicked on (because I need to add a comment to it)?
I've tried to attach a click listener to the div, getting the outerHTML of the target element and trying to get the indexOf document.content, but it's not always working, because there can be similar stuff inside the big string like <p>Hello</p> twice and it will get the first one only.
It's possible that my whole approach is wrong, but I'm not really sure.
Any suggestion is welcome. Thanks!
What you could do is to clone the parent element, add the comment using DOM manipulation and then use the parent element's innerHTML, here is an example:
const parent = document.querySelector('#parent');
parent.addEventListener('click', event => {
event.target.classList.add('toBeModified');
const clone = parent.cloneNode(true);
const node = clone.querySelector('.toBeModified');
const comment = document.createElement('span');
comment.textContent = '(edited)';
node.appendChild(comment);
node.classList.remove('toBeModified');
event.target.classList.remove('toBeModified');
console.log(clone.innerHTML);
});
<div id="parent">
<p>Hello</p>
<p>World</p>
<p>Hello World</p>
<p>Hello</p>
</div>
What this does is to add a class (toBeModified) to the clicked element so it can be easily found once the parent is cloned.

Adding a DOM element by changing innerHtml of a div prevents it to be found later with getElementById?

I have a div and I'm using javascript to add a new element inside it
Original Div:
<div id="foo"></div>
JavaScript:
document.getElementById('foo').innerHTML ="<div id='bar'></div>";
Result
<div id="foo">
<div id="bar"></div>
</div>
But after executing this code I try to retrieve the element (in order to focus on it) doing
document.getElementById('bar')
But this returns an empty object.
So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?
It works perfectly - make sure you're running it in the correct order:
document.getElementById('foo').innerHTML ="<div id='bar'>Bar</div>";
console.log(document.getElementById("bar"));
<div id="foo">Foo</div>
I would suggest using createElement and appendChild
var barDiv = document.createElement('div');
barDiv.id = 'bar';
document.getElementById('foo').appendChild(barDiv);
document.getElementById('bar').innerHTML = 'bar';
console.log(document.getElementById('bar'));
<div id="foo">Foo</div>

Get element's html tag content

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.

Appending a div on unknodw div

I have three divs. How should I append a div onto an unknown div?
<div class="main" >
<div id="drag-box" >
<div id="" class=""> </div>
</div>
</div>
I want to append div on an unknown div which is come after drag-box div. I don't know which div comes after drag-box div. But there must be one div after drag-box div.
$("#drag-box div:first-child").append("<span />");
or
$("#drag-box div").first().prepend("<span>first</span>");
For a complete answers, here it is working:
http://jsfiddle.net/dMUD3/
try this
$("#drag-box div:first-child").attr("id");
Instead of giving you a one liner I would like to give you an indepth solution.
A browser takes your html and parses what is called a DOM Tree out of it.
so if your html is .
<div class="a">
<div class="foo"></div>
<button class="foogle"></button>
</div>
The tree structure will become something like
`-div.a
|-div.foo
`Button.foogle
You should actually look into DOM Api's at MDN
How DOM helps ?
With DOM api's you can actually access the unknown div using the reference to a known div. So if you actually understand your markup and its representation in DOM it should be pretty simple to get reference to nth child of an element;
You can access the child elements by the children attribute.
So
// Get reference to the element.
var parent = document.getElementById("drag-box");
// Use the dom.
var child_i_want = parent.children[0];
// or there is another way
var child_i_reallyWant = parent.firstElementChild;
There are solutions with jQuery but I feel its important for you to Understand basics of DOM even when there are helpful abstraction libraries in existance.
You'll need the + selector. It applies to the object directly following. See here.
.drag-box + div {
}
$('<div></div>').appendTo($('#drag-box div:first'))

Save the parents children in a var to append later

I have a markup in one of my website pages as follows:
<div id="mainPage">
<div>
<div><ul><li>etc.</li></ul>
</div>
<div>
<div><ul><li>etc.</li></ul>
</div>
</div>
What the above means is that there's a main div in my website which has the content. I want to take all the children of the particular div and save it in a var, since I want to use that var later for something like $('resurrectPage').append(someVar); where someVar has the dom elements from the main page div.
How can all the children of a particular element be selected and added to a var?
$('#mainPage').html() would give you the entire thing in a string "<div>
<div><ul><li>etc.</li></ul> </div> <div> <div><ul><li>etc.</li></ul> </div>"
$('#mainPage').children() would give you immidiate children [div,div]
$('#mainPage').find('.div') would giv =e you all the divs inside it [div,div,div,div]
if #mainPage is your main div, you can get of it's children by
var someVar = $('#mainPage').children();
Official api page
I think you're looking for jQuery detach method...
http://api.jquery.com/detach/
It will remove an element and store its contents, ready to be re-appended:
var a = p = $("a").detach()
If you only need the HTML you can save the HTML: var someVar = $("#mainPage").html(); and then append the HTML with the code you already have. Please tell me if I have misunderstood your question.

Categories