I want to use javascript to add a link inside a div, this div doesn't have id , it does has a class though:
<div class="details">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
How to add a link inside the "details" div and above the "delete" link?
The link I want to add is:
Edit
go for jquery, it's simple and clean.
you can grab any element with a particular class say
<div class="className" ></div>
like this
<script>
$('.className');
</script>
now you want to append someother element just before the anchor having delete class, well than you can do this:
$('.delete').before('Edit');
there are other methods also to append an element inside any other element or dom
1. $('.className').append('<div> i will be appended at the bottom of this element</div>');
2. $('.className').after('<div> i will be appended right after this element</div>');
for using jquery, you will need its api, directly use this link in your page or, download the latest jQuery api and use it.
its simpler and easier.
function hasClass(element, className) {
var s = ' ' + element.className + ' ';
return s.indexOf(' ' + className + ' ') !== -1;
}
/**
* from: http://www.dustindiaz.com/getelementsbyclass
*/
function $class(className, context, tag) {
var classElements = [],
context = context || document,
tag = tag || '*';
var els = context.getElementsByTagName(tag);
for (var i = 0, ele; ele = els[i]; i++) {
if (hasClass(ele, className)) {
classElements.push(ele);
}
}
return classElements;
}
then use the $class('delete') to locate the elements, and then prepend new elements
It's always best to search by id, it is most efficient. However if it comes to it, you may find elements by class or tag name as well.
I recommend using jQuery, and changing the existing tag you have:
$('a').attr('href', '#edit_link').text('Edit').removeClass('delete').addClass('edit');
If it is not possible to add an id to the element you're finding, find an element somewhere higher in the tree that has an id, and go from there:
$('#someHigherId > div > a')...
You could use jQuery:
$('div.details a.delete').before('Edit');
You can do it using javascript like this
<script type="text/javascript">
function addtext(what){
if (document.createTextNode){
var link = document.createElement('a');
link.setAttribute('href', '#edit_link');
link.setAttribute('id', 'edit');
link.setAttribute('class', 'edit');
document.getElementsByTagName("div")[0].appendChild(link)
document.getElementById("edit").innerHTML = what;
}
}
</script>
<div class="details" id="mydiv" onClick="addtext('Edit')">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
Using pure JavaScript:
var div = document.getElementsByClassName('details')[0],
deleteLink = div.getElementsByClassName('delete')[0],
editLink = document.createElement('a');
editLink.textContent = 'Edit';
editLink.className = 'edit';
editLink.href = '#edit_link';
div.insertBefore(editLink, deleteLink);
Related
I am trying hide specific Text elements from content by jquery.
HTML:
<div id="name">
Trying hide specific Text elements from content.
</div>
I want this:
<div id="name">
Trying hide <p style="display: none;">specific</p> Text elements from content.
</div>
Or any others simple solution by jquery?
somthing simple like
var nameText = $('#name').text();
var newText = nameText.replace('specific','<p style="display:none">specific</p>');
$('#name').html(newText) // use html() here, not text()
add an id to your p tag and you can hide it by jquery like
$( document ).ready(function() {
$("#p-id").hide();
});
I make function for you
function hideIt(elem, exclude){
var text = elem[0].innerText;
var exculude = exclude;
var match = text.match(exclude);
if(match === null){
console.log('no match founded')
}
else{
for(var i =0 ; i<match.length; i++){
elem[0].innerText = text.replace(match[i],"")
}
}
}
hideIt($('#name'),'specific');
place 1rst param your elem with jquery selector and on 2nd parm the string want to kill
https://jsfiddle.net/xps4553m/5/ for you
I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery
I am trying to have a div element on every page of my site that will contain the product number and then have a link that will put that number at the end.
For example,
<div id="productnumber">01101</div>
https://example.com/#
Then put the contents of the element with id "productnumber" after the # of the link.
Any idea if this is possible? Since this would make life easier than editing all existing pages and their respective php files.
Check for Element.innerHTML. You could use some inline JS and append it to the href-Attribute (which should be were id="purchaseurl" is now)
You can add a simple script to all your pages.
document.addEventListener("DOMContentLoaded", function() {
var productNumber = document.getElementById('productnumber').textContent;
Array.prototype.forEach.call(document.querySelectorAll('a[href~="purchaseurl"]'), function(link) {
// if you want to change the link
var currentHref = link.getAttribute('href');
link.setAttribute('href', currentHref + '#' + productNumber);
// if you want to change anchor text
var currentText = link.innerHTML;
link.innerHTML = currentText + productNumber;
});
});
<div id="productnumber">01101</div>
https://example.com/#
See getElementById, getElementsByTagName, and nextSibling.
var data = document.getElementById('productnumber'),
url = data.nextSibling.nextSibling;
url.innerText += data.innerText;
<div id="productnumber">01101</div>
https://example.com/#
I'm looking to convert a function that selects by id to select the next instance of a given class.
Here is the code.
function swap3(oldDivId, newDivId) {
var oldDiv = document.getElementById(oldDivId);
var newDiv = document.getElementById(newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
Suppose you have this HTML:
<div id="test"></div>
<img>
<br>
<div></div>
<input>
<div class="abc">Found it</div>
<div class="cdf"></div>
Updated at 2021
The original answer is quite old now. Since the original question have the jQuery tag, the answer keeps valid and usable. But for those coming here with the hope to see an updated JavaScript code with no dependency on jQuery, take a look on how querySelector is a awesome nowadays:
const next = document.querySelector('#test ~ .abc')
next.textContent = 'Yeah, you found it!'
So the secret is to use the general sibling combinator that matches all iterations of the second element, but with querySelector that returns only the first match.
Original answer
So you select the first div by id:
var some = $("#test");
Then you want to find the next div with the class abc:
var next = some.nextAll("div.abc");
Suppose you want a variable as the className:
var x = "abc";
var next = some.nextAll("div." + x);
If I understand your question:
function nextItem(className) {
return $('#ID').closest('.' + className);
}
using closest: http://api.jquery.com/closest/
Select by ID in jQuery:
$('#class_name')
Select by class in jQuery:
$('.class_name')
Get the next item in jQuery:
$('.class_name').next('.class_name')
Using this, you can do something like
// Something to remember the current element
var currentElement = false;
function getNext(className)
{
// First time, there will be no current element
if (!currentElement)
{
currentElement = $('.' + className);
return currentElement;
}
// Other times...
currentElement = $(currentElement).next('.' + className);
return currentElement;
I have a div with id="images".
The div contains some images that are each wrapped in an anchor tag with no target attribute.
I'd like to insert script into my page that pulls a reference to each of these anchor elements and ads a target="new" attribute to them (in the runtime) so that when they are clicked they each open in a new window.
I don't want to hardcode the target attributes on the anchor tags. This is a post deployment workaround. I'm not using jquery in this application.
<div id="images"><img src="foo.png" />...etc </div>
No jQuery required! You can do this easily using native DOM methods:
// Find all the anchors you want to modify
var anchors = document.getElementById('images').getElementsByTagName('a'),
i = anchors.length;
// Add the target to each one
while(i--) anchors[i].target = "new";
You can traverse all the anchor elements inside your div, first by looking up the div itself, and then you can use the element.getElementsByTagName method:
var imagesDiv = document.getElementById('images'),
images = imagesDiv.getElementsByTagName('a');
for (var i = 0, n = images.length; i < n; i++) {
images[i].target = "_blank";
}
function replaceAllAnchors(Source,stringToFind,stringToReplace){
//sample call: body=replaceAllAnchors(body,'<a ','<a target="_blank" ');
var temp = Source;
var replacedStr="";
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
replacedStr=replacedStr+temp.substr(0,temp.indexOf("/a>")+3);
temp=temp.substr(temp.indexOf("/a>")+3);
index = temp.indexOf(stringToFind);
}
replacedStr=replacedStr+temp;
return replacedStr;
}
Why can't you use jQuery? I've added this here for other people who google.
It's 1 line of code in a loop:
$('#images a').each(function(){ $(this).attr('target', '_blank'); });
Now isn't that much more simple? Use jQuery if you can.