Im using the below code to replace the text within the h1 tag, but its not getting effected. I want to replace "sample" to "new sample". I'm doing wrong?
<div class="content">
<h2>sample</h2>
</div>
var t = jQuery('.content');
t.children("h2").each(function() {
var contents = jQuery(this).contents();
jQuery(this).replaceWith(new sample);
});
use .html() to set html.try this:
$('.content h2').html('new sample');
Working Demo
If you want to replace some part of content then try this:
jQuery('.content h2').each(function(i, v) {
$v = $(v);
$v.html($v.html().replace('sample', 'new sample'));
});
jsFiddle
Use jQuery's .text()
$(".content h2").text("new sample");
FIDDLE
You can do that without jQuery:
var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
Set .text()
t.children("h2").text('new sample'));
If you want to set .html() content
t.children("h2").html('new sample'));
Child Selector (“parent > child”)
$('.content > h2').html('new sample');
Related
I am trying to echo all the paragraphs of a specific class. The source code has this structure:
<div class='example'>
<p> this is the first paragraph </p>
<p> this is the second paragraph </p>
</div>
I have tried different ways (getElementsByTagName and stuff like this but they didn't work). Could you suggest me something?
Simply get the value by classname.
Use Js Function getElementsByClassName
Try below code for Javascript :
var x = document.getElementsByClassName("example").innerHtml;
console.log(x);
alert(x);
Also working jsfiddle with javascript - https://jsfiddle.net/ayh0gk7s/1/
If you are prefer to use jQuery then try below code :
$('.example p')
jsfiddle link for jquery - https://jsfiddle.net/3nhb1agu/
Fetch them via XPath:
$doc = new DOMDocument;
$doc->load('file.html');
$xp = new DOMXPath($doc);
$pars = $xp->query('//div[contains(#class, "example")]/p');
// For exactly one class:
//$pars = $xp->query('//div[#class = "example"]/p');
foreach ($pars as $p) {
var_dump($p->nodeValue);
}
The code fetches text representations of the paragraph nodes.
In JQuery, you can print the parent children element. Try this !
$(document).ready(function(){
$("div.example").children("p").each(function(){
alert($(this).text());
console.log($(this).text());
});
});
Using jQuery:
$('.example p')
This should hopefully get you the desired paragraphs.
You can use querySelectorAll.
var myParagraphs = document.querySelectorAll('.example p');
for (var i = 0 ; i < myParagraphs.length ; i++) {
console.log(myParagraphs[i]);
}
<div class="albumclass">
<img width="100" height="100" data-assigned-id="9" src="/Content/images/fold.png">
<p>15Sep2015</p>
</div>
The above code is generated dynamically through jQuery. After that I need to display the content of <p> ie., '15Sep2015' by clicking on the above image. How can I get this? I used the below code:
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).closest("p").text();
alert(txt);
}
But that alerts nothing.It not possible to take content implicitly because a lot of similar div will be there.
The .closest() gets the parent. So use .siblings() or .next. I have used .next():
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).next("p").text();
alert(txt);
}
You can go up to parent div and find p using find() :
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).closest("div").find('p').text();
alert(txt);
}
Hope this helps.
$('.albumclass').on('click', function(){
var p_text = $(this).children('p').text();
alert(p_text);
});
Why not try adding a class to the 'p' tag so that u can get the element by a class selector and see
var text = $('.class').text();alert(text);
or u may try
$(document.body).on('click','.class',function(){
});
I have tested every solution I have found on Internet, but none of them works.
I have this HTML:
<h4>Códigos disponibles:<span id="codesQuantity">#Model.ExternalCodesForThisProduct</span></h4>
And this Javascript:
$('#eCodesFrm').on('submit', function (e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var availableCodes = $("#codesQuantity");
var totalCodesUsed = 0;
alert(availableCodes);
$('#eCodesFrm *').filter(':input').each(function () {
if (this.name.match(/.Quantity$/)) {
totalCodesUsed = totalCodesUsed + parseInt(this.value, 10);
}
});
But availableCodes is [object Object].
What am I doing wrong?
If you need the inner element try .html(). As long as it's plain text in there there shouldn't be a problem.
To get the text inside the <span> use .text():
jQuery("#codesQuantity").text() //or $("#codesQuantity").text() if $ is jQuery in your code.
The problem here is that you're assigning a jQuery object to your variable, and not the content of the element. To extract the text inside the <span>, you should use either .html() or .text(), and do this instead:
var availableCodes = $("#codesQuantity").text();
My html markup is looking like this : <div id="somediv"> [whitespace] text</div> and I'm adding this value like inside an input element like this:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text());
jQuery('input[name="search"]').keyup();
});
This works fine but the problem is that is adding the value with the whitespaces and I don't want this.
I've found this jquery method jQuery.trim() which seems to remove all the whitespaces but I don't know how can I use it inside my actual function.
Can someone give me some suggestions on how achieve this ?
Chain the method to the text
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
Use trim(). Like:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
I recommend you "cache" your jQuery calls, so I did it by using oSearch. (Line 1)
then to answer your jQuery.trim question... do it like this
var oSearch = jQuery('input[name="search"]');
jQuery('.votefilters span a:first').on('click', function(event) {
var text = jQuery('.myo-poll-bar.firstoption').text();
text = jQuery.trim( text );
oSearch.val( text );
oSearch.keyup();
});
jQuery.trim('yourtext') similar to this:
jQuery('.votefilters span a:first').on('click', function (event) {
var $input = jQuery('input[name="search"]');
var newText = jQuery('.myo-poll-bar.firstoption').text();
var trimmedText = jQuery.trim(newText);
$input.val(trimmedText);
$input.keyup();
});
DEMO - Using jQuery.trim();
I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed