jQuery syntax not setting object property - javascript

My jQuery question I beleive is pretty simple, which is driving me insane that I can't get it.
I have an object with a property "content", I want to be able to take that object, manipulate the property "content" with jQuery and then overwrite the value with the new value jQuery creates.
Example:
o.content = "<div><span>hello</span></div>";
$('div', o.content).addClass('test');
At this point I want o.content to be equal to <div class='test'><span>hello</span></div>
I can not for the life of me figure out the syntax. Any help is really appreciated.

This will give you a string <div class="test"><span>hello</span></div> if this is what you want:
$(o.content).addClass('test').wrap('<div>').parent().html();

Parse the html in o.content, add the class, append the parsed html to a new <div>, and get the html of the new div:
o.content = "<div><span>hello</span></div>";
var el = $(o.content).addClass('test');
o.content = $("<div>").append(el).html();
Edit: This assumes you want o.content to still contain a string, rather than a jQuery object. In that case, it's simpler:
o.content = $(o.content).addClass('test');

from the docs of the jquery function, context must be
A DOM Element, Document, or jQuery to use as context
Your context (o.content) is a string. Also, the jQuery function is not able to select the entire context, it can only select elements in that context.
Try this instead:
// make o.content a jquery element, not a string
o.content = $("<div><span>hello</span></div>");
// select on something inside the context (inside the div), not the div itself
$('span', o.content).addClass('test');
http://jsfiddle.net/JfW4Q/

I don't think you can lookup an element from a string like that.. I would rather do it like below,
var content = "<span>hello</span>";
content = $('<div/>', {class: 'test'}).html(content)
DEMO: http://jsfiddle.net/k4e5z/

You want the following
o.content = "<div><span>hello</span></div>";
// Create a jQuery object you can call addClass on
var docFragment = $(o.content);
docFragment.addClass('test');
// Since there's no outerHTML in jQuery, append it to another node
var wrapper = $('div');
docFragment.appendTo(wrapper);
// The HTML of the wrapper is the outerHTML of docFragment
console.log(wrapper.html()); // outputs <div class='test'><span>hello</span></div>

Why not do it all in one line:
var o = {};
o.content = $( "<div></div>" ) // create element
.addClass('test') // add class
.html( '<span>hello</span>' ); // append content
Fiddle: http://jsfiddle.net/kboucher/eQmar/

o.content = $("<div><span>hello</span></div>");
o.content.addClass('test');
o.content is a jQuery object in this example, as opposed to just a string. Here's a demo on jsfiddle: http://jsfiddle.net/cvbsm/1/

Related

get content of some tags inside a variable

var a = $('#txta').val();
console.log(a);
result is complete html code from this url
Now I want to get content of all #artikal-naziv tags (there are 96)
var b = a.find("#artikal-naziv").text();
console.log(b);
Result:
Uncaught TypeError: a.find is not a function
Any help?
Actually you are calling .find() on a string and not in a DOM element.
Because from $('#txta').val() you are getting a string, that's why you got Uncaught TypeError: a.find is not a function, because string doesn't have .find() method.
You should change it to:
var a = $('#txta');
Then you can write:
var b = a.find("#artikal-naziv").text();
Note:
Now I want to get content of all #artikal-naziv tags (there are 96)
You can't set the same id #artikal-naziv for multiple elements (96), the id should be unique in the page.
Another thing .val() call assumes that your element is a form element, you can't call .val() on a div or a span, if it isn't a form element use .html() instead.
Because "a" is not a jQuery object - it's usually a string containing value of the returned element (txta).
Use $(a).find(...) instead - that will probably do it.
Ref link: https://stackoverflow.com/a/3532381/3704489
As per what I can make out of your description, you are getting HTML as string using var a = $('#txta').val();. If this is true, you will have to create an in-memory element and set this string as its HTML.
Then you will have an in-memory DOM section that you can query on.
You can try something like this:
var html = '<span><p id="artikal-naziv">bla bla</p></span>';
var $tempElement = $('<div>').html(html);
console.log($tempElement.find('#artikal-naziv').text());
// or using vanilla JS
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
console.log(tempElement.querySelector('#artikal-naziv').textContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
.val() takes out the value from the element....Whereas all DOM operations are done on the element... because function like .find() , .hide() , .show() , .closest() etc are used with the element not the value
The Following modifications should work...
var a = $('#txta'); // $("#ID") returns the element
console.log(a.val()); // $("#ID").val() returns the value
the result is complete html code from this URL
Now I want to get content of all #artikal-naziv tags (there are 96)
var b = a.find("#artikal-naziv").text(); // .find() easily works on element
console.log(b);
Simply use .find to find children and .closest to find parents:
<div class='a'>
<div class='b'>
<div class='c'></div>
<div class='c'></div>
<div class='c'></div>
</div>
</div>
js:
var a = $('.b');
a.find('.c'); // Will return all the objects with the class c
a.closest('.a'); // Will return the first parent with the class a

Delete elements in a javascript string

I have a string containing html elements, now I need to select some elements and remove them from the string.
In JQuery I tried the following:
html_string = "<ul><li data-delete>A<li><li>B</li></ul>";
html_clean_string = $(html_string).remove('[data-delete]').html();
This is what I expected:
"<ul><li>B</li></ul>"
But I got the same original string. So how can I use CSS selectors to remove html elements from a string?
You can do it like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var elems = $(html_string);
elems.find('[data-delete]').remove();
var html_clean_string = elems[0].outerHTML;
You had a couple of issues:
.remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.
Since you want the host top level HTML too, you will need the .outerHTML.
You had mistakes in your html_string.
Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/
You can also save a little jQuery with more chaining like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerHTML;
Working jsFiddle:http://jsfiddle.net/jfriend00/wmtascxf/

Can jQuery work for html strings that are not in DOM?

I have an html string that I created with a template.
This string has an html table with a bunch of rows, I'd like to manipulate this string using jquery, for example to add some classes to some rows based on logic, or other manipulation and then have jquery return a string. However, it seems that jQuery only manipulates the DOM. But I don't want to post this string into the DOM yet.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>";
//Something like
var newString = $(htmlString -> '#bla').addClass('blaClass');
// this syntax is obviously wrong, but what I mean is I'm trying
// to look inside the string not the dom
Or maybe it's better to post this string into an invisible div first and then manipulate it with jquery?
Parse it to a variable, manipulate, then append:
var origString = "<table><tr id='bla'>...";
origString = $.parseHTML(origString);
$(origString).find("tr").addClass("test");
$("body").append(origString);
Concept demo: http://jsfiddle.net/6bkUv/
Yeah, you can add a class without appending it to the dom.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>",
newString = $('<div>'+origString+'</div');
newString.find('#bla').addClass('blaClass');
console.log(newString.html());
Yes, you can definitely manipulate a string with jQuery. Here is what the following code does:
Declares a div to wrap the string in
Wraps the string in the div and does the manipulation
Finally, produces the manipulated string
No interaction with the DOM whatsoever.
var htmlString = "<table><tr id='bla'>...";
var div = $('<div/>');
div.html( htmlString ).find( '#bla' ).addClass( 'class' );
var newString = div.html();
WORKING JSFIDDLE DEMO
//OUTPUT
Original: <table><tr id='bla'><td></td></tr></table>
New: <table><tbody><tr id="bla" class="class"><td></td></tr></tbody></table>
NOTE: Please note that if your table string does not have a tbody element jQuery will include it as that makes for valid table markup.
The answers were too complicated. The answer is just a dollar sign and some parentheses:
var queryObj = $(str);
So
var str = "<table><tr>...</tr></table>"
var queryObj = $(str);
queryObj.find('tr').addClass('yoyo!');
// if you use 'find' make sure your original html string is a container
// in this case it was a 'table' container
$("body").append(queryObj);
works just fine..

jQuery throws an error that element.find() is not a function

I have written a small JS to iterate through a set of matched elements and perform some task on each of them.
Here is the code:
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = element.find(".product-meta").clone();
});
When I console log element it outputs properly and the exact objects. Why should jquery throw this error?
because element is a dom element not a jQuery object
var eachProductContent = $(element).find(".product-meta").clone();
Inside the each() handler you will get the dom element reference as the second parameter, not a jQuery object reference. So if you want to access any jQuery methods on the element then you need to get the elements jQuery wrapper object.
You are calling .find() on a plain JS object, But that function belongs to Jquery object
var eachProductContent = $(element).find(".product-meta").clone();
You can convert it to a jquery object by wrapping it inside $(). And in order to avoid this kind of discrepancies you can simply use $(this) reference instead of using other.
Use $(this) for current Element
var eachProductContent = $(this).find(".product-meta").clone();
you should change "element" to "this":
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = $(this).find(".product-meta").clone();
});

JS DOM equivalent for JQuery append

What is the standard DOM equivalent for JQuery
element.append("<ul><li><a href='url'></li></ul>")?
I think you have to extend the innerHTML property to do this
element[0].innerHTML += "<ul><li><a href='url'></a></li></ul>";
some explanation:
[0] needed because element is a collection
+= extend the innerHTML and do not overwrite
closing </a> needed as some browsers only allow valid html to be set to innerHTML
Hint:
As #dontdownvoteme mentioned this will of course only target the first node of the collection element. But as is the nature of jQuery the collection could contain more entries
Proper and easiest way to replicate JQuery append method in pure JavaScript is with "insertAdjacentHTML"
var this_div = document.getElementById('your_element_id');
this_div.insertAdjacentHTML('beforeend','<b>Any Content</b>');
More Info - MDN insertAdjacentHTML
Use DOM manipulations, not HTML:
let element = document.getElementById('element');
let list = element.appendChild(document.createElement('ul'));
let item = list.appendChild(document.createElement('li'));
let link = item.appendChild(document.createElement('a'));
link.href = 'https://example.com/';
link.textContent = 'Hello, world';
<div id="element"></div>
This has the important advantage of not recreating the nodes of existing content, which would remove any event listeners attached to them, for example.
from the jQuery source code:
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem ); //<====
}
});
},
Note that in order to make it work you need to construct the DOM element from the string, it's being done with jQuery domManip function.
jQuery 1.7.2 source code
element.innerHTML += "<ul><li><a href='url'></li></ul>";

Categories

Resources