HTML
<textarea id="photo-42-9" class="comment_box">Write a comment...</textarea>
jQuery code that doesn't work, what am I missing?
$('#photo-42-9').prepend("<div>blah</div>");
EDIT
Corrected the ids mismatch, still doesn't work though
prepend() adds the specified mark-up into the object returned by the jQuery selector (in this case the textarea). A textarea can contain only text, no other child elements; therefore you're trying to create invalid html.
If you want to put the <div> before the textarea:
$('<div>blah</div>').insertBefore('#photo-42-9');
If you want to prepend new text into the textarea:
$('#photo-42-9').val(
function(i,val){
return 'blah ' + val;
});
References:
prepend().
insertBefore().
val().
The contents of a textarea element are treated as text, not as HTML. They are parsed into the element's value property. You can't edit the content of the element: you have to edit its value.
The nice, jQuery-ish way of doing this is with val and its callback syntax:
$('#photo-42-9').val(function(i, oldVal) {
return "<div>blah</div>" + oldVal; // return the desired value
});
jsFiddle
Note that I have also corrected the selector: you had an additional 9 in the ID, so it wouldn't have found the element.
#Bob: In addition to what David Thomas said, your item has an id of photo-42-9 and your selector is looking for photo-42-99
Suggested Fix:
$('#photo-42-99').text( $('#photo-42-99').text() + "<div>blah</div>" );
Related
I am trying to add some text to an existing element using textContent. But when I use +=(addition assignment) operator but in the result, already existing tags like b has lost its effect. I think I am just adding to it, but it also has effect in the previous content. Can anyone explain why? I checked the docs but didn't find anything about this.
HTML:
<div id="divA">Something<b>bold</b></div>
JS
const some = document.getElementById("divA");
some.textContent += "Hi"; // This results in : "Something boldHi" without the bolded formatting.
some.textContent = some.textContent + "Hi"; //This too results in the same!
Thanks in advance!
The .textContent value of an element returns just that - the text content, which is plain text, not the HTML markup of the contents.
If you do
some.textContent += "Hi"
The text content of the container will be retrieved, which will not contain any tags - eg
<div id="divA">Something<b>bold</b></div>
will retrieve:
Something bold
Concatenating onto that and then assigning the result back to the .textContent of the element results in the element's descendants replaced with a single text node, where the text node's value is the value assigned.
If you use .innerHTML += instead, the prior HTML markup of the descendants will be preserved - but the descendants will all be re-parsed according to the HTML markup assigned, so event listeners and related things that depend on DOM elements will be lost. A better option is to use .insertAdjacentHTML, which does not require re-parsing of the descendants.
An even better option would be to append a node itself instead of trying to write HTML markup (which is potentially unsafe), eg
some.appendChild(document.createTextNode('Hi'))
When you are taking the textContent then you will get Somethingbold which is just plain text wihtout HTML tags
console.log(some.textContent); // Somethingbold
You are appending the textContent, instead you shold use innerHTML
const some = document.getElementById("divA");
some.innerHTML += "Hi"; // This results in : "Something boldHi" without the bolded formatting.
some.innerHTML = some.innerHTML + "Hi"; //This too results in the same!
<div id="divA">Something<b>bold</b></div>
Supposedly a jquery object can be initialized from string. This can often happen when processing ajax results, i.e. I'm trying to replicate http://api.jquery.com/jQuery.post/
However, I'm seeing strange behavior:
function test() {
var content = $("<html><body><div>hello</div><div>world</div></body></html>");
alert("content.text() = " + content.text());
alert("content.html() = " + content.html());
}
The first alert shows: content.text() = helloworld
The second alert shows: content.html() = hello
What's happening here?
Solution
Thanks everyone for the explanations. I ended up adding another layer of <div> to have a single child of <body>, as in
<html>
<body>
<div> <=== added
<div>hello</div>
<div>world</div>
</div>
</body>
</html>
When parsing HTML fragments containing a body element, browsers in general (and jQuery does this as well) will disregard everything except what's inside the body element. So what you have there ends up being equivalent to:
var content = $("<div>hello</div><div>world</div>");
alert("content.text() = " + content.text());
alert("content.html() = " + content.html());
You end up with a jQuery object with two elements in it: The div elements.
In jQuery, normally accessor functions (html, val, css, etc.) only use the first element in the set when you use them as getters, and that's what html is doing above. text is an unusual accessor function in jQuery: It gives you the combined text of all of the elements in the set, not just the first.
We can see this in the docs, but it's still surprising. From html:
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
From text:
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
(My emphasis in both cases.)
Browsers remove those html and body elements. The content collection has only 2 div elements.
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.
This is the string representation of your content collection:
content.map(function() { return this.outerHTML || this.nodeValue; }).get().join('');
// -> <div>hello</div><div>world</div>
.text() method returns textContent/nodeValue of all the elements in the collection:
content.text(); // -> helloworld
.and .html() method returns innerHTML of the first element in the collection:
content.html(); // -> hello
This is what your content looks like to a browser:
"content = " Object { 0: <div>, 1: <div>, length: 2 }
Basically this is in some kind a set of 2 elements.
And here's what http://api.jquery.com/html/ say:
Get the HTML contents of the first element in the set of matched elements
I have a span with a text inside it like :
<span class="characters-count">(160 Characters Left)</span>
given the span a class in this case .characters-count , when i tried class selector using jQuery to get the text inside span :
$(".characters-count")[0].text();
it returns undefined !
However this selector works well :
$("span.characters-count").text();
anyone can explain what is happening ?
$("span.characters-count").text();
In our case you work with jQuery Object that has text method
$(".characters-count")[0].text();
In this case you work with actual DOM element (like document.getElementByClassName('characters-count')[0]) that does not have text method
Use
$(".characters-count").text();
Demo
console.log($(".characters-count:first").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="characters-count">(160 Characters Left)</span>
try something like this:
$(".characters-count:first").text()
Check here, why it was not working for you.
//This will return dom element, so it doesn't have `text()` method, that's why it was throwing error for you.
console.log($(".characters-count:first")[0]);
// This will return object of an element, you can use jQuery selectors to get first element from collection and set text to it
console.log($("span.characters-count"));
console.log($("span.characters-count:first").text
);
you need to use innerText instead of text() when you use $(".characters-count")[0] check DEMO
$(".characters-count")[0].innerText
I have an input tag:
<input type="text" value="04/09/2013" class="date-time-date width-100 hasDatepicker" name="booking_info[to_time_24_date]" id="to_time_24_date" readonly="readonly">
i need to get all the content in input tag (all content shown above) but when i use
$('#to_time_24_date').html();
it returns nothing. How can i get this content?
Try this:
document.getElementById('to_time_24_date').outerHTML;
Use this simple method in order to get all of your input field HTML:
$('#to_time_24_date').get(0).outerHTML;
I have made a JsFiddle Test Demo for you, Please follow this link. It will give the same thing you are looking for, in alert.
http://jsfiddle.net/jpaYK/
You may try the outerHTML property.
$('#to_time_24_date').get(0).outerHTML
you can use outerHTML
$('#to_time_24_date').get(0).outerHTML; // $('#to_time_24_date')[0].outerHTML;
Demo: Fiddle
without jQuery
document.getElementById('to_time_24_date').outerHTML
html() gets the inner HTML, HTML of the elements inside this element.
Check the answer here:
Get selected element's outer HTML
The accepted answer uses a nice trick in the answer to this question. It creates another element (but doesn't add it to the page), clones the element it wants inside the created element, and then gets the inner HTML of the created element, which is the HTML of the clone, which is the same HTML of the element we want.
$("<div>").append($('#to_time_24_date').eq(0).clone()).html();
// or
$("<div>").append(document.getElementById('#to_time_24_date').clone()).html();
However, see other answers as well, turns out there is a simpler way you can try too, there's a property outerHTML you can use as:
$('#to_time_24_date')[0].outerHTML
Which has decent browser support as per:
https://developer.mozilla.org/en-US/docs/Web/API/element.outerHTML?redirectlocale=en-US&redirectslug=DOM%2Felement.outerHTML
var html = "<input";
$.each($("#"+to_time_24_date)[0].attributes, function(i, attr){
html += ' '+attr.name+'="'+attr.value+'"';
});
html += " />";
alert(html);
jsfiddle
<input type="text" value="04/09/2013" class="date-time-date width-100 hasDatepicker" name="booking_info[to_time_24_date]" id="to_time_24_date" readonly="readonly">
This does not have any "Content" or "HTML" it does have attributes, and you can get the attributes with the attr method from jQuery.. $('input[type="text"]').attr('id'); would return the id attribute.
If you are just looking for the entered value of the input tag (what is typed in) then use $('input[type="text"]').val(); to get the value.
I hope this helps
here's a jsfiddle example
http://jsfiddle.net/LUep8/
I am new to Jquery and I've had a look through the replies on here but I can't find any specific answers to my question.
I have a (ASP) generated table a snippet of which is:
<a href="javascript:__doPostBack('gv2','Select$15')"
style="color:White;">S</a></td><td style="font-size:XX-Small;">1104</td>
<td style="font-size:XX-Small;">320.20.0116.090</td>
<td style="font-size:XX-Small;">*Not Found*</td>
What I'm trying to do is highlight the *Not Found text and then disable the preceeding href so the link cannot be clicked.
I have developed the following selector:-
$('td').highlight('Not Found').each(function(){$(this).prev("a").removeAttr("href")});
The highlight selector works but the removeattr doesn't. Syntax is probably incorrect but any pointers would be very useful.
Answered:- This works
$("td:contains('*Not Found*')").each(function(){$(this).parent().find('a').removeAttr("href")})
I'd personally suggest:
// selects all 'td' elements
$('td').filter(function(){
// retains only those whose text is precisely '*Not Found*'
return $.trim($(this).text()) == '*Not Found*';
// moves to the closest (ancestor) 'tr'
// finds the 'a' element within that 'tr' element
// sets the 'href' attribute to be equal to '#'
}).closest('tr').find('a').attr('href','#');
JS Fiddle demo.
Alternatively, rather than setting the href to #, you could just remove the a element by unwrapping its contents:
$('td').filter(function(){
return $.trim($(this).text()) == '*Not Found*';
}).closest('tr').find('a').contents().unwrap();
JS Fiddle demo.
References:
attr().
closest().
contents().
filter().
find().
jQuery.trim().
text().
unwrap().
try $(this).prev().find("a").removeAttr("href")}
also removing the link might not work.
try replacing the href with #