I'm trying to extract multiple <p></p> elements and append them to a single div. I can only seem to get the first paragraph. Any idea?
I'm using this code:
$("#result").append($wikiDOM.find('p').html());
You don't need to use .html()
$("#result").append($wikiDOM.find('p')); //Remove .html()
When you use .html() it will give you the HTML of first element only, not all of the paragraphs in the jQuery set. But note that using append on an element that's already in the document will move it from its old location to its new one (whereas appending the HTML of an element just copies it).
You don't need to get the html() from the selected elements - you can append them directly:
$("#result").append($wikiDOM.find('p'));
Related
I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?
I need a solution in Javascript only as jQuery isn't being used
Thanks for any help!
Fidde: https://jsfiddle.net/p7g7mkxs/
What I've tried:
<p class="hello">hello</p>
<p class="hello">helloLINK</p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.
You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement)). In the case of an HTMLAnchorElement, that means you just get the href. Proof:
console.log(
String(document.querySelector("a"))
);
Hey
To append an element to the end of another element's child list, use appendChild:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(To insert it elsewhere, use insertBefore. Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)
Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0], use querySelector(/*...*/), which returns the first match or null.
In addition to what #t-j-crowder said, you can also use outerHTML to accomplish the task:
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);
Using JQuery I have appended a div into a container called .mobile-sub. I call the append by doing:
$('.s2_error').addClass("revive");
$('.revive').parent(".mobile-sub").append('<div>mydiv</div>');
It works fine but the problem is that it is placing the div after the .s2_error tag whereas I need it to be placed before so the end result HTML will look like this:
<div>mydiv</div>
<p class="s2_error">Error</p>
Any ideas?
Using various options like below
insertBefore
$("<div>mydiv</div>").insertBefore('.mobile-sub .s2_error');
OR by writing another selector inside your insertBefore
$("<div>mydiv</div>").insertBefore($('.revive').parent(".mobile-sub").find('.s2_error'));
Meaning
$('thisElementShouldBe').insertBefore('thisElement');
prepend
$('.revive').parent(".mobile-sub").prepend('<div>mydiv</div>');
So <div>mydiv</div> will always be added as the first child of mobile-sub
before
$('.revive').parent(".mobile-sub").find('.s2_error').before("<div>mydiv</div>");
You can do it two ways:
Before
$(".s2_error").before("<div>mydiv</div>");
InsertBefore
$("<div>mydiv</div>").insertBefore(".s2_error");
Both do the same but they are syntactically different.
You can use .insertBefore()
Insert every element in the set of matched elements before the target.
$("<div>mydiv</div>").insertBefore('.s2_error');
OR, .before()
Insert content, specified by the parameter, before each element in the set of matched elements.
$('.s2_error').before("<div>mydiv</div>");
Note: The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target.
You want to add element as first child. You need to use .prepend() instead of .append():
$('.revive').parent(".mobile-sub").prepend('<div>mydiv</div>');
You can also use .insertBefore ():
$("<div>mydiv</div>").insertBefore('.s2_error');
or .before():
$( ".s2_error" ).before( "<div>mydiv</div>" );
.insertBefore( target )
Description: Insert every element in the set of matched elements
before the target.
or
.before( content [, content ] )
Description: Insert content, specified by the parameter, before each
element in the set of matched elements.
I am having an issue were jQuery is not inserting the specified html element into all instances of #element. However, it is only inserting it into the first element but not the other 3 with that id.
var htmlcode = '<div class="block"></div>';
$('#element').html(htmlcode);
If I switch it to $('div') it will work but this isn't what I want. I need to have this inserted into all divs with the id of #element. From what I understand from the documentation this should be working?
Ids must be unique on a page. As they are implemented as a fast-lookup dictionary there is only one element stored against each key/id.
jQuery and JavaScript can only see the first one because of this.
Use a class instead.
e.g.
$('.element').html(htmlcode);
I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.
I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.
For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)
And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.
Am I understanding it correctly? Or are there any difference between those three?
element.innerHTML
From MDN:
innerHTML sets or gets the HTML syntax describing the element's descendants.
when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.
node.appendChild
From MDN:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.
element.insertAdjacentHTML
From MDN:
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. [ ... ]
This method is also supported by all browsers.
....
The appendChild methods adds an element to the DOM.
The innerHTML property and insertAdjacentHTML method takes a string instead of an element, so they have to parse the string and create elements from it, before they can be put into the DOM.
The innerHTML property can be used both for getting and setting the HTML code for the content of an element.
#Guffa did explain the main difference ie innerHTML and insertAdjacentHTML need to parse the string before adding to DOM.
In addition see this jsPerf that will tell you that generally appendChild is faster for the job it provides.
One that I know innerHTML can grab 'inner html', appendChild and insertAdjacentHTML can't;
example:
<div id="example"><p>this is paragraph</p><div>
js:
var foo = document.getElementById('example').innerHTML;
end then now
foo = '<p>this is paragraph</p>';
DOCS:
appendChild
insertAdjacentHTML
innerHtml
innerHTML vs appendChild() performance
insertAdjacentHTML vs innerHTML vs appendChild performance
the main difference is location (positioning) :
(elVar mean element saved to variable)
** elVar.innerHTML: used to sets/get text and tags (like ) inside an element (if u use "=" it replace the content and "+=" will add to the end.
** divElvar.appendChild(imgElVar): to add pure element to the end of another element (or start with prepend) .
** insertedElVar.insertAdjacentElement(beforebegin,targetElvar): it insert element into spicific location before elVar (after it with "afterend").
-innerText: can replace/get/insertOnEnd text.but can read tags and text inside element with display:hidden , cant insert on start .
-innercontent : show all text inc hidden , cant read html tags and it put empty spaces instead of them , cant insert on start
-innerHTML: read all set all , cant insert on start
-prepend : insert text at start of elvar (but cant use to get/replace text or html)
prepend was needed for start, after it made its easy to make append , not for a need , its just bcz lol
There are several elements that are selected by $(".foo"). $(".foo").text() returns the text of each element concatenated together. I just want the text of one element. What is the best way to do this?
$(".foo")[0].text() fails.
You want to use .eq(0), like this:
$(".foo").eq(0).text()
When you do $(".foo")[0] or $(".foo").get(0) you're getting the DOM Element, not the jQuery object, .eq() will get the jQuery object, which has the .text() method.
Normally using the # selector syntax selects one element by id attribute value. Do you have more than one element with the same id attribute value? If so, then you need to correct your HTML. id attribute values should be unique within a document.
The items in the jQuery array always return the dom elements (not the jQuery wrapped elements). You could do something like:
$($("#foo")[0]).text()