Change text id span via JavaScript [duplicate] - javascript

This question already has answers here:
How can I change an element's text without changing its child elements?
(16 answers)
Closed 1 year ago.
I have next html:
<label for="user_name">
<abbr title="required">*</abbr>
Name
</label>
And I want to change label caption to Title with jquery. So I do
$('label[for=user_name]').html('Title')
And it replaces all inner html (including abbr tag)
So, what's the easiest way to replace only Name?

If you use contents() method it will also return text nodes. Since jQuery doesn't have text node methods, convert last node to a DOM node
$('label[for="user_name"]').contents().last()[0].textContent='Title';
Demo: http://jsfiddle.net/yPAST/1/

Sorry for the late reply... But here is a way to do so using only jQuery:
$('label').contents().last().replaceWith('Title');

It may not be the prettiest way, but this works:
var $label = $('label[for=user_name]');
$label.html($label.html().replace("Name", "Title"));

You can select only the abbr element, store it, and then replace the whole content with the stored element plus the changed caption:
​$('label[for="user_name"]').each(function(){
var a = $(this).children('abbr');
$(this).html(a).append('Title');
});
See this fiddle​

you can use replace accomplish this
var html = $('label[for=user_name]').html().replace('Name','Testing');
$('label[for=user_name]').html(html);
check it : http://jsfiddle.net/DyzMJ/

Evans solution added to jquery fn to make it's use comfortable:
// get/change node content not children
jQuery.fn.content = function( n ){
var o = $(this).clone();
var c = o.children().remove();
if (typeof n === "string" ){
o.html(n);
$(this).html(c).append(n);
}
return o.html();
}
Usage :$('myselector').content('NewContentString');

This is the solution that worked for the most browsers
$('label[for="user_name"]').contents().last()[0].nodeValue = 'Title';
This one came close but gave issues in ie8 since textContent is not supported
$('label[for="user_name"]').contents().last()[0].textContent='Title';

if you are manipulating more than 1 label you can select each label and replace text with jquery:
$('label[for="user_name"]').contents().last().replaceWith("Title");
and for the second label :
$('label[for="user_lastname"]').contents().last().replaceWith("Title2");
and so on ...

Related

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

Remove a character from the middle of a string: without removing inner element

This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:
<label class="option" for="edit-attributes-21-33">
<input type="radio" id="edit-attributes-21-33" name="attributes[21]"
value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>
I started with this
$(".option").each(function(index, value) {
$(this).text( $(this).text().replace("+", ""));
})
This removes the "+" but also strips out the input element. So then I tried:
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);
})
This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.
You can achieve what you want using your code by using .html() instead of .text():
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).html(newString);
});
Here's the JQuery .html() method ref: https://api.jquery.com/html/
Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/
I also slightly modified your <input> end tag to make it XHTML compliant.
What you're looking for is called a textNode. I gave your label an ID to make it easier, but the priciple remains the same for other selectors:
var node = document.getElementById("example").childNodes[2];
node.nodeValue = node.nodeValue.replace("+", "");
With a simple demo.
You should try to use plain JS as much as you can in favour in jQuery. Plain JS is often a lot faster than jQuery is.
After the comment, if you don't know the exact position of the textnode, check this.
Late answer, just for the sake of showing a different approach using jQuery.
Here you would keep the input state, and wouldn't have the risk of replacing chars that you don't want to. Let's say you used + somewhere else, not just on the label text.
$(function () {
$('label.option').each(function () {
var label = $(this);
var input = $('input.form-radio', this);
var text = label.text();
// Clean up the label contents.
label.empty();
// Replace the char occurrences.
text = text.replace(/\+/g, "");
// Append both the input and the modified text.
label.append(input).append(text);
});
});
Demo

Grabbing text from a span tag

I have some code for Javascript using jQuery, and I've been wondering how to fix an element of it.
var dataGiven = +$("span.cost-in-usd:first-child").text();
However, the span tag is:
<span class="cost-in-usd" data-se="product-usd-value">42</span>
Is there a way of modifying my code in order for it to recognise data-se?
Yes, use data.
var datase = $('.cost-in-usd').data('se');
Some links;
http://api.jquery.com/jquery.data/
Here's a jsfiddle
The following will return the value of attribute
$('.cost-in-usd').attr('data-se');

How to get text around an element?

If I have
<div id='wrapper'>
<fieldset id='fldset'>
<legend>Title</legend>
Body text.
</fieldset>
</div>
How could I retrieve the "Body text" without retrieving the text inside of legend tag?
For instance, if I wanted to see if the text inside the fieldset contains the word "body" and change that word, while ignoring whatever might be in the legend? innerHTML retrieves all text from all children nodes.
Use of jQuery wouldn't be a problem.
$("#fldset").contents().eq(2).text();
Without a library --
var fldset = document.getElementById("fldset"),
txt = fldset.lastChild.textContent || fldset.lastChild.innerText;
alert(txt);
This will get all the text nodes of fldset leaving out any other element and it's content:
var fldsetContent = $('#fldset').contents();
var text = '';
$(fldsetContent).each( function(index, item) {
if( item.nodeType == 3 ) text += $.trim($(item).text());
});
alert( text );
Live example
$('#fldset').clone().find('legend').remove().end().text()
But you should also search around the SO
Using .text() to retrieve only text not nested in child tags
Clip content with jQuery
I can't think of a way other than
$("#result").html($("#wrapper").text().replace($("legend").text(),""));
but there should be a more elegant way. You can also create a new element as a copy of this one, remove all the children and get text. Hmm... That would be:
var newElement = $("#fldset").clone();
newElement.children().remove();
$("#result").html(newElement.text());
So doesn't matter how many and which type of children node has, this would work. Here: http://www.jsfiddle.net/wFV4c/
To turn all plain text nodes inside the field set red:
jQuery.each($('#fldset').contents(),function(index,value){
if(value.textContent == value.nodeValue){
$(this).wrap('<span style="color:red;" />')
}
});

select created element

$(iframe).bind('keypress', function (e) {
if (e.which == 13) {
var range = iframe.getSelection().getRangeAt(0);
var nodeText = $(range.startContainer, iframe).parent().html();
var leftPart = nodeText.substr(0, range.endOffset);
var rightPart = nodeText.substr(range.endOffset);
$(range.startContainer, iframe).parent().replaceWith('<big>' + leftPart + '</big><p>' + rightPart + '</p>');
return false;
}
});
I've got iframe with some content, e.g:
<p>someText</p>
When i place cursor between "some" and "text", and press enter, i want it to be splitted into this:
<big>some</big><p>Text</p>
everything seems to be working ok, but I also need to change cursor position to the beginnings of this: <p>Text</p>
I know how to set cursor position, but I need to select that element. just $('p', iframe) won't work, because I can have multiply <p> items in iframe. any ideas?
This is an unholy mix of DOM, which considers everything in terms of nodes and offsets, and jQuery-ish HTML-as-strings. The two do not mix well. You've misunderstood the endOffset and startOffset properties of DOM Ranges: they're not offsets within the innerHTML of the container. I suggest looking at MDC or the spec and refactoring your code to only use DOM nodes and not strings of HTML.
Denis ,
Give a common class name to all of them , so that it will effect on the elements.
I would add a dynamic id attribute (or use the metadata plugin) using jQuery to identify the split paragraph. And based on the identified split string place the cursor before the <p> tag. Do make sure to remove the id attribute (or some metadata) once you are done placing the cursor, so that any other splits or a backspace on the same <p> doesn't result in unintended consequences
Hope that helps
I found a nice solution without adding id or class to element. i changed this:
$(range.startContainer, iframe).parent().replaceWith('<big>'+leftPart+'</big><p>'+rightPart+'</p>');
to this:
var leftObject = $('<big>'+leftPart+'</big>');
var rightObject = $('<p>'+rightPart+'</p>');
$(range.startContainer, iframe).parent().replaceWith(leftObject);
leftObject.after(rightObject);
now i got both elements selected in leftObject and rightObject

Categories

Resources