Add innerHTML before an element in JavaScript? [duplicate] - javascript

This question already has answers here:
How can I implement prepend and append with regular JavaScript?
(12 answers)
Closed 8 years ago.
Now I am not talking about creating children or a child node, I literally mean HTML. This is what I want to do:
I have a basic node, for example:
<div id="foo"></div>
And I have a string of HTML, that I want to append before that element (kinda like what innerHTML does, with the difference, that I am obviously putting it before, not inside), e.g.:
"<span>hello, world</span><div></div>Foo<img src="logo.png" />Bar"
Now I want to insert that HTML before the div, so my outcome would be:
<span>hello, world</span><div></div>Foo<img src="logo.png" />Bar<div id="foo"></div>
Is there any way I can do this in JavaScript (without any library)? Thanks!

The most elegant and shortest solution is to call insertAdjacentHTML on foo with "beforeBegin" and html string as arguments. Pure JS.
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO

The easiest way is to use a helper element for the parsing, then grab its contents. Like this:
var foo = document.getElementById("foo");
var parent = foo.parentNode;
var helper = document.createElement('div');
helper.innerHTML = yourHTMLString;
while (helper.firstChild) {
parent.insertBefore(helper.firstChild, foo);
}
There, we create a temporary helper, then assign the string to it to generate the contents, then move those child nodes (which are a mix of elements and text nodes) into foo's parent node, just in front of foo.
Note that depending on the HTML content, you may need a different helper element. For instance, if the string defined table rows or cells.
Complete example - live copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Inserting Before</title>
</head>
<body>
<div>Before foo</div>
<div id="foo"></div>
<div>After foo</div>
<script>
setTimeout(function() {
var yourHTMLString = "<span>hello, world</span><div></div>Foo<img src=\"logo.png\" />Bar";
var foo = document.getElementById("foo");
var parent = foo.parentNode;
var helper = document.createElement('div');
helper.innerHTML = yourHTMLString;
while (helper.firstChild) {
parent.insertBefore(helper.firstChild, foo);
}
}, 500);
</script>
</body>
</html>

Related

JavaScript: Instead of passing "this" as an argument, how can I make function which will be called on it as an object?

I'm JavaScript beginner and am still grasping some concepts around it, so sorry if the question is dumb or it's already answered, but I didn't know what to search for, as the language terminology is still kinda foreign to me (both JavaScript and English). Currently I'm trying to master "this" keyword and trying to minimize JS code inside HTML file and move as much as possible to external files.
This is my question:
Let's say I want to change paragraph's value from Hello World! to foo bar by clicking on paragraph itself, just by using "this" keyword and some JavaScript.
I can do it in external file like:
<!--index.html-->
<p onclick="setParagraphText(this, 'foo bar')">Hello World!</p>
----------------------------------------------
//script.js
function setParagraphText(paragraph, value) {
return paragraph.innerHTML = value;
}
Or inline, inside tag:
<p onclick="this.innerHTML='foo bar'">Hello World!</p>
My question is: is it possible to do a combination of these 2 ways, so that the p value is not passed as an argument, but instead the function is invoked on it as an object (as a similar to 2nd example), but still keep the method of doing it in external file (like in 1st example)?
Something along the lines of this.function(value) instead of function(this, value)
<!--index.html-->
<p onclick="this.setParagraphText('foo bar')">Hello World!</p>
----------------------------------------------
//script.js
function setParagraphText(value) {
//something with innerHTML = value; or whatever will work
}
Thanks in advance!
You can add a data- attribute to your p tag which would store the data you want your text to change to (ie: "foo bar"), and then use addEventListener to add a click event-listener to paragraph tags which have this particular data- attribute. By doing this, you're handing over the javascript logic to the javascript file, and thus limiting the JS written within your HTML file.
See example below:
const clickableElements = document.querySelectorAll('[data-click]');
clickableElements.forEach(elem => {
elem.addEventListener('click', function() {
const value = this.dataset.click;
this.innerHTML = value;
});
});
<p data-click="foo bar">Hello World!</p>
<p data-click="baz">Hello Moon!</p>
First of all, if you want to be able to call your function on this, you have to know what the keyword this here represents. One simple way to do it is to console.log it.
So, this is the DOM element you have your inline javascript on ! Confirmed here: this in an inline event handler. Okay, if you want to have more information, console.log paragraph.constructor.
So, it's a HTMLParagraphElement. That's what you would get if you call this:
document.createElement("p");
So, if you want to be able to call this.setParagraphText, it comes down to calling setParagraphText on an HTMLParagraphElement object. But in order to do that, HTMLParagraphElement has to implement it and one way to do this, as subarachnid suggested, is to add the function to its prototype so that it is shared by all instances of it. If you think this would be useful, take a look at Web Components.
Here is a link: Extending native HTML elements.
Basically, you do it like this (and the cool thing here is the functionality, that is changing its content when clicking on it, will be encapsulated within the class):
<!DOCTYPE html>
<html>
<body>
<script>
// See https://html.spec.whatwg.org/multipage/indices.html#element-interfaces
// for the list of other DOM interfaces.
class CoolParagraph extends HTMLParagraphElement {
constructor() {
super();
this.addEventListener('click', e => this.setParagraphText('new value'));
}
setParagraphText(v) {
this.innerHTML = v;
}
}
customElements.define('cool-paragraph', CoolParagraph, {extends: 'p'});
</script>
<!-- This <p> is a cool paragraph. -->
<p is="cool-paragraph">Cool paragraph! Click on me and the content will change!</p>
</body>
</html>
So you don't even have to write inline Javascript anymore!
But if you want to have it your way and add your inline javascript, it's fine.
<!-- Note the this.setParagraphText(), now it works! -->
<p is="cool-paragraph" onclick="this.setParagraphText('foo bar')">Cool paragraph! Click on me and the content will change!</p>
<!DOCTYPE html>
<html>
<body>
<script>
// See https://html.spec.whatwg.org/multipage/indices.html#element-interfaces
// for the list of other DOM interfaces.
class CoolParagraph extends HTMLParagraphElement {
constructor() {
super();
//this.addEventListener('click', e => this.setParagraphText('new value'));
}
setParagraphText(v) {
this.innerHTML = v;
}
}
customElements.define('cool-paragraph', CoolParagraph, {extends: 'p'});
</script>
<!-- This <p> is a cool paragraph. -->
<p is="cool-paragraph" onclick="this.setParagraphText('foo bar')">Cool paragraph! Click on me and the content will change!</p>
</body>
</html>
I don't know if that answers your question, but that should hopefully points you in the right direction.
For your code to work you would have to enhance the HTMLElement prototype with your setParagraphText method (which is basically just a wrapper for this.innerHTML = value):
HTMLElement.prototype.setParagraphText = function(value) {
this.innerHTML = value;
};
Now something like this should work:
<p onclick="this.setParagraphText('foo bar')">Hello World!</p>
But I would strongly advise against modifiying native prototypes (older browsers like IE 9 don't even allow such a thing afaik).
Currently I'm trying to [...] minimize JS code inside HTML file and move as much as possible to external files.
Then how about having no JS code inside your HTML? This lets you kill two birds with one stone:
document.getElementById("clickme").addEventListener("click", function() {
this.innerHTML = "foo bar"
})
<p id="clickme">Hello world!</p>
The listener you add with addEventListener will be invoked with this being the element that the listener was added on.
Dunno if this is what you're after, but this in the function is referring to the function itself, but you can send in a scope with .call(this, arguments) which means that referring to this in the function is actually the scope of the HTML element.
I'm showing two ways of how you can handle this, with either a data attribute or sending in a new value as a parameter.
function setParagraphText(newValue) {
this.innerText = this.dataset.text + " + " + newValue;
}
<p data-text="foo bar" onclick="setParagraphText.call(this, 'foo yah')">Hello World!</p>
Also read: Javascript call() & apply() vs bind()?

jQuery selector is overlooking elements from a separate context

I'm making an ajax request to a page on my site with this element as a direct child of the body tag:
<div class="container" id="wantme"><div class="content"></div></div>
There's only one .container, and I want to grab its ID which I don't know.
As far as I can tell, this code should do what I want:
$.get('/page', function(data) {
id = $('.container', data).attr('id');
});
But the .container selector fails to find anything.
I did find these two workarounds. I can find .content, and I can climb up the tree like this:
id = $('.content', data).parent().attr('id');
But I can't leap directly there.
I found this workaround elsewhere on StackOverflow that works:
html = $('<div></div>').html(data);
id = html.find('.container').attr('id');
But why is it that the seemingly obvious answer doesn't work?
UPDATED ANSWER: I'll leave my original answer at the bottom, however I'm concerned it may misbehave depending on browser. jQuery's .html() makes use of Javascript's innerHTML - some browsers choose to strip <head> and <body> tags when using innerHTML, whereas others do not.
The safest method to achieve what you're after may still be the workaround you mentioned, like so:
var data = '<!doctype html><html><body><div class="container" id="findme"><div class="content"></div></div></body></html>';
var $container = $("<div />").html(data).find(".container");
var id = $container.attr("id");
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information as to the browser-related issues can be found here.
PREVIOUS ANSWER:
When you pass HTML to a jQuery element, it will ignore the <body> tags, as well as anything outside of them. Given the data string in your JSFiddle, $(data) will create something that looks like this:
<div class="container" id="findme">
<div class="content"></div>
</div>
As you can see in the HTML above, your .container isn't inside of $(data) - it is $(data).
Because $(data) is representing your .container element, you should just be able to do $(data).attr("id") to retrieve what you're after.
var data = '<!doctype html><html><body><div class="container" id="findme"><div class="content"></div></div></body></html>';
var id = $(data).attr('id');
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You are not getting the ID from $('.container', data).attr('id'); is because you are setting the value of the second parameter. What you want to do is this: $('.container ' + data).attr('id');.
Update:
If data is a string then you should convert it into a DOM element: $('.container', $(data)).attr('id');

jQuery "add" Only Evaluated When "appendTo" Called

this has been driving me crazy since yesterday afternoon. I am trying to concatenate two bodies of selected HTML using jQuery's "add" method. I am obviously missing something fundamental. Here's some sample code that illustrated the problem:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="para1">This is a test.</p>
<p id="para2">This is also a test.</p>
<script>
var para1 = $("#para1").clone();
var para2 = $("#para2").clone();
var para3 = para1.add(para2);
alert("Joined para: " + para3.html());
para3.appendTo('body');
</script>
</body>
</html>
I need to do some more manipulation to "para3" before the append, but the alert above displays only the contents of "para1." However, the "appendTo appends the correct, "added" content of para1 and para2 (which subsequently appears on the page).
Any ideas what's going on here?
As per the $.add,
Create a new jQuery object with elements added to the set of matched elements.
Thus, after the add, $para3 represents a jQuery result set of two elements ~> [$para1, $para2]. Then, per $.html,
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
So the HTML content of the first item in the jQuery result ($para1) is returned and subsequent elements (including $para2) are ignored. This behavior is consistent across jQuery "value reading" functions.
Reading $.appendTo will explain how it works differently from $.html.
A simple map and array-concat can be used to get the HTML of "all items in the result set":
$.map($para3, function (e) { return $(e).html() }).join("")
Array.prototype.map.call($para3, function (e) { return $(e).html() }).join("")
Or in this case, just:
$para1.html() + $para2.html()
Another approach would be to get the inner HTML of a parent Element, after the children have been added.

After cloning an element find the original element in the document

I clone my mainSection like this (I have to clone it because, there are new elements added to #main over AJAX, and I don't want to search through them):
$mainSection = $('#main').clone(true);
then i search through the cloned main section for an element:
var searchTermHtml = 'test';
$foundElement = $mainSection.filter(":contains('"+searchTermHtml+"')");
When I find the string 'test' in the #mainSection I want to get the original element from it in the $mainSection so I can scroll to it via:
var stop = $foundElementOriginal.offset().top;
window.scrollTo(0, stop);
The question is: how do I get the $foundElementOriginal?
Since you're changing the content of #main after cloning it, using structural things (where child elements are within their parents and such) won't be reliable.
You'll need to put markers of some kind on the elements in #main before cloning it, so you can use those markers later to relate the cloned elements you've found back to the original elements in #main. You could mark all elements by adding a data-* attribute to them, but with greater knowledge of the actual problem domain, I expect you can avoid being quite that profligate.
Here's a complete example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div id="main">
<p>This is the main section</p>
<p>It has three paragraphs in it</p>
<p>We'll find the one with the number word in the previous paragraph after cloning and highlight that paragraph.</p>
</div>
<script>
(function() {
"use strict";
// Mark all elements within `#main` -- again, this may be
// overkill, better knowledge of the problem domain should
// let you narrow this down
$("#main *").each(function(index) {
this.setAttribute("data-original-position", String(index));
});
// Clone it -- be sure not to append this to the DOM
// anywhere, since it still has the `id` on it (and
// `id` values have to be unique within the DOM)
var $mainSection = $("#main").clone(true);
// Now add something to the real main
$("#main").prepend("<p>I'm a new first paragraph, I also have the word 'three' but I won't be found</p>");
// Find the paragraph with "three" in it, get its original
// position
var originalPos = $mainSection.find("*:contains(three)").attr("data-original-position");
// Now highlight it in the real #main
$("#main *[data-original-position=" + originalPos + "]").css("background-color", "yellow");
})();
</script>
</body>
</html>

Why does appendChild only work when I remove the docType

When I put any sort of doctype declaration like <!DOCTYPE html >, appendChild does not work.... Why?
<form>
<script language="javascript">
function function2() {
var myElement = document.createElement('<div style="width:600; height:200;background-color:blue;">www.java2s.com</div>');
document.forms[0].appendChild(myElement);
}
</script>
<button onclick="function2();"></button>
</form>
I'm trying to get data from a popup window's parent opener...is that possible? The data can be a string literal or value tied to the DOM using jQuery .data()
If you're having this problem in IE, it's probably because the presence of a DOCTYPE declaration forces the browser into "standards-compliance" mode. This can cause code that doesn't conform to expected standards to break.
In your case, it's probably because document.createElement doesn't accept an HTML fragment - it accepts an element name, e.g. document.createElement('div').
Try replacing your function body with something like this:
var myElement = document.createElement('div');
myElement.style.width = '600px';
myElement.style.height = '200px';
myElement.style.backgroundColor = 'blue';
myElement.appendChild(document.createTextNode('www.java2s.com'));
document.forms[0].appendChild(myElement);
Read up on the document object model here: https://developer.mozilla.org/en/DOM
Also, jQuery is good for easily creating elements using the syntax you specified.

Categories

Resources