Using inline style with jQuery appended element - javascript

I'm writing a user script in Greasemonkey and I am currently adding elements to a text box. I have tried unsuccessfully to use inline CSS within the created element like so
CSS
.append($("<p style="color:blue">"))
Is this even possible to do with jQuery? I couldn't find any examples of this searching around and I'm still really new to coding, so I apologize if this has been answered before.

Supposing you want to append a inline-styled <p> tag to a <div> tag you have to use:
var parentNode = $('div');
var childNode = $('<p>');
childNode.css('color', 'blue');
parentNode.append(node);

The last post asking really well to question but your first approach works also (you just forget the '/' at the end).
Supposing you want just adding a simple "p" empty element, you can just do this (with Jquery):
$(element).append('<p style="color:red" />')
or if you want to add a p no empty element do this :
$(element).append('<p style="color:red" > My text </p>')
It's the shortest way to do that but the last post show a more cleaning technic to do that.

Related

Removing specific tag but keeping its child element as it is

I am trying to copy the HTML content of specific tag and and then removing the specific HTML tag and attaching the copied element of that tag to the sibling of removed tag. Is there way to fix solve this issue?
For e.g HTML is like this :
<p>This is sample <span id ="1">text <strong>to v<span>erify</span></strong> the</span> issue</p>
I am expecting output like this :
<p>This is sample text <strong>to v<span>erify</span></strong> the issue</p>
Now if you observe the span element with id="1" has been removed , but its parent contents are still there which are appended to the siblings of deleted span(id=1) element.
I have too low of a rep to be able to comment.
Just as a reminder you can name an elements HTML5 id starting with a digit. But if you do, you can only target that element using the id from javascript not using CSS.
It's hard to tell the problem because I can't see the sample code. Like #FedeSc pointed out you probably forgot to put it in.
Please edit the question with the sample code and I'll gladly see if I can help you.

How can I make my Javascript code select all 'b' tags on a page instead of only the first one?

We have a very large website that is quite old and has a lot of 'b' tags. My boss wants to change them to 'strong' tags but this will require a lot of time to change manually so she was hoping we could change it with some code.
I had a nice bit of JQuery code that worked (intermittently), but I couldn't get it to work on the site as it uses JQuery 1.9.1 and cannot be upgraded.
I then found this piece of Javascript which does what I need but only works on the first 'b' tag on the page and all others stay as 'b' tags. I don't know enough about Javascript selectors to change the firstChild selector.
<script>
function replaceElement(source, newType) {
// Create the document fragment
const frag = document.createDocumentFragment();
// Fill it with what's in the source element
while (source.firstChild) {
frag.appendChild(source.firstChild);
}
// Create the new element
const newElem = document.createElement(newType);
// Empty the document fragment into it
newElem.appendChild(frag);
// Replace the source element with the new element on the page
source.parentNode.replaceChild(newElem, source);
}
// Replace the <b> with a <div>
replaceElement(document.querySelector('b'), 'strong');
</script>
You might use querySelectorAll:
Array.from(document.querySelectorAll('b')).forEach(e=>{
replaceElement(e, 'strong');
});
But this is really a xy question. You really should do the change server side, for example by using some search/replace (learn to use your code editor). You're adding to the code debt here.
Note also that there's no obvious reason to prefer strong over b in HTML5.
Use getElementsByTagName(). It's more efficient than querySelectorAll because it doesn't have to parse selectors, and it describes better what you are really trying to do - get elements by tag name.
var elements = document.getElementsByTagName("b");
replaceElement(elements[0], "strong");
replaceElement(elements[1], "strong");
replaceElement(elements[2], "strong");
You can also iterate over this collection by using Array.from().
You would be better off finding the source of the <b> tags and changing them there as Denys has mentioned.
Updating the DOM would have little benefit and would cause performance issues when there are many tags on a page.
Does this system use a CMS or database to store the content? I would look to use something like these 2 SQL queries to replace them across the site:
update content_table set content_column = replace(content_column, '<b>','<strong>');
update content_table set content_column = replace(content_column, '</b>','</strong>');

Using HTML in a jQuery string

I'm not experienced with JS, so please excuse the presumably very beginner question.
I have this line:
$el.text(type + "|");
I need to wrap the "|" in span tags such as '<span class="">|</span>' though when I do so it simply prints out the tags as text as opposed to embedding them as HTML wraps.
How do I go about doing this?
Use .html() to print out HTML content, text prints out plain text.
$el.html(type + "<span class=''>|</span>");
or
$el.html(type).append($('<span/>',{text : '|'}));
You can dynamically create your span element using this syntax:
var $el = $('<span>').html('|');
This fiddle contains my solution. The fiddle uses a button to make it clear what is actually happening. I also added a style to the span so you can see it being added.
https://jsfiddle.net/g0n71se7/
$("#test").append("<span> | <span>");
By using the jQuery append you will insert content to the end of an element. You could alternatively use prepend to insert at the start of an element.

Replacing text with javascript?

After much trial an error and some progress I still can't mange to change every instance of ,- with kr on my website.
I'm very much a beginner at JS and have pieced together the following code from several sources. Is the code the problem or something else?
function skrivkr() {
var skrivkr = $('div').text().replace(/\,-/g, 'kr');
$('p').html(skrivkr);
}
window.onload = skrivkr();
Update:
Thanks for the replies. The site loads jquery 1.10.7.
#Niet the Dark Absol: No, I don't want to put anything in p elements. How do I remove that part? I just want to find all ,- and simply replace with kr without changing any formatting.
Update
OK! Progress, kind of. The ENTIRE content of every <strong> and <dd> now changes to (0), instead of kr. With the odd exception of those tags including ,-. I haven't designed the site myself.
If it helps, one of the ,- appears in the following markup:
<a href="xxxx" rel="nofollow">
<span class="amount">1</span>
<span class="photo">
<img src="xxxx" alt="product name" width="62" height="42">
</span>
<span class="description">
Prtoduct name
<strong>4444,-</strong>
</span>
</a>
And the lastest script I'm applying is:
$(document).ready(function() {
$('strong, dd').html($('strong, dd').html().replace(/,-/g, 'kr'));
});
As has been mentioned innumerable times here on SO, do not try to manipulate the DOM as a string. Pain awaits.
Instead, traverse the DOM, finding text nodes, and perform whatever transformation you want to make on each text node. There are many ways to do that.
In your case, you have many problems, as mentioned already by some of the commenters and responders:
You're setting window.onload to undefined (the result of calling skrivkr), instead of to skrivkr itself.
You're extracting the text value of an element, which consists of the concatenation of all text down all levels, performing the replacement, then sticking it back in with html. This will wipe out all the element structure below.
Minor point, but there's no need to escape the comma in the regexp.
You're extracting the textual content of all div elements in the entire document, transforming it, then adding that back as the content of all p elements in the entire document. It's hard to imagine that's what you want to do.
You can update the content of each div like this
$(document).ready(function() {
$('div').each(function(){
var newText = $(this).html().replace(/,-/g, 'kr');
$(this).html(newText);
});
});
You can remove the var "newText = " and replace it with $(this).html($(this).html().replace(/,-/g, 'kr'));
The first example is easier to understand perhaps if you are new to programming.
You will, however only change the content of text placed in tags.
I would place the text to replace in a div with some predefine class, like "autoKronor", it would then look like this:
<div class="autoKronor">123,-</div>
and
$(document).ready(function() {
$('.autoKronor').each(function(){
var newText = $(this).html().replace(/,-/g, 'kr');
$(this).html(newText);
});
});
to en sure that only text you intended to change gets changed..
Example here: http://jsfiddle.net/akm1uw8h/2/
Also note the use of $(document).ready(); instead of window.onload. It does what you intended to do with window.onload.
if you really want to change EVERY single instance of ",-" to "kr" then you could do this:
$(document).ready(function() {
$('body').html($('body').html().replace(/,-/g, 'kr'));
});
But i strongly advice against the last example because it will be the slowest to compute and more importantly you might change stuff you don't intend to, like any script block inside the page body (with that i mean other javascripts)

Cannot match pattern for wordpress empty paragraph tag

For some reason wordpress randomly inserts "blank" paragraph tags on my page. I'm finding it difficult to match the tag.. It seems like it's not completly empty but some weird character I cannot see, it's not there in the source code but generated by javascript so it's very hard to figure out what it is!!
My JS file is loaded last in <head>.
I'm new to regex in javascript..
it looks like this in firebug (not sure if there is a small space/tab/something or not)
<p></p>
My javascript to remove it:
jQuery(window).load(function() {
var page = jQuery('body').html();
page.replace('/\<p\>\S*\<\/p\>/', '');
jQuery('body').html(page);
});
Use jQuery empty selector instead which select all elements that have no children (including text nodes). Try this.
jQuery(window).load(function() {
jQuery('body').find('p:empty').remove();
});
You know the exact string, so what's the matter with just matching just that?
page.replace('/\<p\>\<\/p\>/','');

Categories