Before appending more code, I want to make sure:
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
isn't already on the html page inside the div where id='faqs'
<div id='faqs'>
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
</div>
What is the best way of doing this with jquery or javascript?
Thanks
The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
// element isn't on the page
}
You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>") == -1) {
$('#faqs').append ("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>");
}
if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
//does'nt exist
}
If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('<a />')
.attr('href', 'index.php?option=com_content&view=article&id=36')
.html('hello')
.appendTo($('#faqs'));
However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;
UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';
// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');
var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
// do something
} else {
// do something else
}
Here's a working example -> http://jsfiddle.net/Uzef8/2/
Related
I'm trying to replace all occurences of '$' (dollar sign) in a web page with another string.
The problem is that there may be some <script> tags that may contain the '$' (jQuery code) that I don't want to change.
For example:
document.body.innerHTML = document.body.innerHTML.replace(/\$/g, 'xxx'); seems to work, but also replaces '$' from any <script>$('...')...</script> parts.
Is this achievable?
Thank you in advance.
EDIT: I cannot modify the way the page is generated or change all other js parts - neither use some server-side logic. I can only add some custom js code
You can filter out the script tags
[].slice.call(document.body.children).forEach(function(element) {
if ( element.tagName.toLowerCase() != 'script' ) {
element.innerHTML = element.innerHTML.replace(/\$/g, 'xxx');
}
});
FIDDLE
This is not recursive, which means it only works for script tags directly under the body tag, not script tags that are nested deeper
function textNodes(main) {
var arr = [];
var loop = function(main) {
do {
if(main.hasChildNodes() && (["STYLE","SCRIPT"].indexOf(main.nodeName)==-1)){
loop(main.firstChild);
} else if(main.nodeType === 3) {
arr.push(main)
}
}
while (main = main.nextSibling);
}
loop(main);
return arr;
}
textNodes(document.body).forEach(function(a){a.textContent=a.textContent.replace(/\$/g,'€')});
Based on this DOM walking example
hello everyone javascript don't add the class to html
$(".ocmessage").each(function(){
var text = $(this).find('p').html();
if(strpos(text,"<b>"+name+"</b>")!==false) $(this).addClass("quoteme");
});
this code should detect if in <p>...</p> there are name of some member and if there is javascript should add class quoteme
how can i fix it?
I think you mean this. BTW, name isn't defined.
var name = ''; // change the value
if(text.indexOf("<b>"+name+"</b>") > -1) {
$(this).addClass("quoteme");
}
Assuming ocmessage is a div or another contain class.
Take a look at : http://jsfiddle.net/40vv7dbk/
$(".ocmessage").each(function () {
var $this = $(this);
var text = $this.find('p').html();
var name = "Ben"
// Will be -1 if not found.
if (text.indexOf(name) > -1) {
$this.addClass("quoteme");
}
});
What it is doing, is when the document is ready, going through all the Divs with the class ocmessage, looking for a tag, and then checking if a name is in there. If it does, I add the class quoteme.
Your elements with class ocmessage may contain more than one paragraph. So inside the first each-loop we have to do a second loop through all <p> like so:
$(".ocmessage").each(function(){
var $T = $(this);
$T.find('p').each(function() {
var text = $(this).html();
// find username and prevent multiple class adding
if(text.indexOf("<b>"+name+"</b>") > -1) {
$T.addClass("quoteme"); return false; // stop loop when class is added
}
});
});
Working FIDDLE here. Credits to Amit Joki.
This is a very poor way to accomplish the task. Here's the more standard jquery way to do it.
$(".ocmessage").has('p b:contains('+name+')').addClass("quoteme");
I've been searching for a day or so how to do something with JS or jQuery and found a couple of solutions but nothing solid yet.
I want to use this:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
And I want the output to be:
<h2> This is an H2 </h2>
I know I can achieve this by doing:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
...But I would like to not do a manual search and replace on my code in those blocks and rather have it done on the fly in the browser. Is this possible?
I'm pretty noob with jQuery so I've tried .replaceWith or JavaScript's .replace but so far I've not gotten where I need to be with it. I'm either replacing the whole tag or doing something else wrong.
My question is: How would I write a simple jQuery (or regular JS) to help me replace my < and my > with HTML entities like < and > inside my <code> tags.
I appreciate any help, Thanks.
UPDATE:
I managed to get it working nice how #Prisoner explained, it's very nifty, however this in my particular case needed a little extending because I have more than one block of code with the .codeIt class, so I had to make it check each element and output... otherwise it would keep making the same output (like the first block)
Here is the fiddle
Thanks to everyone for their answers.
Assuming you just want to escape all HTML:
$(".codeIt").text($(".codeIt").html());
Plain JS for single code element
var myCode = document.getElementById('mycode');
myCode.innerHTML = myCode.innerHTML.replace(/</g,'<').replace(/>/g,'>')
Plain JS for multiple code elements
var codeEls = document.getElementsByTagName('code');
for(var i in codeEls)
{
if(parseInt(i)==i)
{
var codeEl = codeEls[i];
if(codeEl.className.match(/\bcodeIt\b/)!==null) codeEl.innerHTML = codeEl.innerHTML.replace(/</g,'<').replace(/>/g,'>')
}
}
or jQuery
$(".codeIt").each(function() {
$(this).html(
$(this).html().replace(/</g,'<').replace(/>/g,'>')
);
});
You could use the text function of jquery:
var myText = $('.codeIt').html();
var escapedText = $('.codeIt').text(myText).html();
var t = $('.codeIt').html();
$('.codeIt').text(t).html();
Look at this fiddle http://jsfiddle.net/kU8bV/1/
$('code').html($('code').html().replace(/</g, '<').replace(/>/g, '>'));
Assuming you want to code all the html in codeIt class :
<script type="text/javascript">
function htmlEncode(value){
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
} else {
return '';
}
}
$('.codeIt').each(function() {
myEncodedString = htmlEncode($(this).html());
$(this).html(myEncodedString);
});
</script>
I'm in a bit of a pickle. What I'm trying to achieve is to remove a div IF it is empty and then do what I have to afterwards which is the easy bit. The hard part is trying to remove the empty tags. I'm using DNN and it likes to put in empty tags like p and br. I want to be able to remove them before performing my check. Here is my code so far
$(document).ready(function(){
var element = document.getElementsByTagName("p"); //Need to remove all tags. not just P
element.parentNode.removeChild(element); //Doesn't target which child
if( !$.trim( $('#container2Test').html() ).length ) {
alert("empty");
$('#container2Test').remove();
$('#container3Test').css({'width' : '50%', 'background-color' : '#3F0'});
$('#container3Test').append("This is some content");
}
else{
alert("not empty");
}
});
The html:
<div id="container1Test" style="width:30%; height:10em; background-color:#000;">
</div>
<div id="container2Test" style="width:50%; height:10em; background-color:#666;">
<p></p><br /><p></p>
</div>
<div id="container3Test" style="width:20%; height:10em; background-color:#F66;">
</div>
I've tried many options to try and remove the tags but I've had no such luck :( Please help!
As far as your container2test block goes, try using .text() instead of .html(). This will ignore the empty tags that get inserted and focus only on the text content.
Regarding the piece above it, I'm not quite sure what you're trying to achieve. I don't think it's needed if you implement the change I mentioned earlier.
I think this will be the solution you'll need... Check out that:
var elmsToClear = $('#container1Test, #container2Test, #container3Test');
elmsToClear.each(function(){
while($(this).find('*:empty').remove().length); // recursivly kill all empty elements
if(!$(this).find('*').length){ // if no elements left - kill the parent
alert($(this).attr('id') + ' is empty...');
$(this).remove();
}
else{ // there is something in here...
alert($(this).attr('id') + ' is NOT empty...');
}
});
>>> The JS-Fiddle of the Problem with Solution <<<
Greetings ;)
Notice that getElementsByTagName is plural:
var elements = document.getElementsByTagName("p");
for (var n=0; n < elements.length; n++) {
var element = elements[n];
element.parentNode.removeChild(element); // should work now
}
There is a removeChild() function. So why can't you do something like this:
$('div').each(function(){
if(this.innerHTML == ''){
this.parentNode.removechild(this);
}
});
(Haven't tested this)
I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
});
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/