Modify attribute href via jQuery

Asked

Viewed 2,686 times

0

I need to know how I change the links and images of a page via jQuery.

I have to make dynamic updates on a certain page and I need to create a script for this, that changes images and links.

Example:

<a href="link1"> <img src="imagem1"></a>
<a href="link2"> <img src="imagem2"></a>

Like, in this example I know that the href contains link1, link2 and that the tag img contains imagem1, imagem2

I need to know if I can create a script that captures the information the user enters and tracks the tags and automatically convert.

Imagine the user puts a link http://wikipedia.org.link1, in which case it would alter the href link1, the same would be for images.

  • 1

    Always change to what’s after the last . ? Or what exactly is the rule ?

  • The rule would be as follows: I would create a field (text box) and play the path of the images and links that I would like to change and these same data would change the data of index.html. Type, the script would consider the information typed in the field and make a comparison (type one contains in the link and images), more or less like this. HTML <a href="eusouolink1"> <img src="imagem2.png"></a> Text field In this case, with the script, the user would update the content with a new link and image, but containing the information in the href and img tags

2 answers

1

To avoid typos it is good to use another way to choose which option to change. Could use a select, for example.

Using a select you can do this with

  1. The function val to know
    • what is the value in a input where the user typed. Ex: var novovalor = $("input").val()
    • the option chosen by the user (link1, Link2 ...). Ex: $("select").val()
  2. The function attrto modify the value of an element property. For example: $("a:first").attr("href", novovalor)
  • 1

    Thank you very much, you’ve helped me a lot :)

  • You’re welcome. If you consider that my answer solved your question, please choose as a solution (click on the arrow below the number of votes). If you still have any questions, ask here.

0

You can change with the jquery attr() function:

$('#elemento').attr('href', 'link que será passado')
$('#elemento').attr('src', 'source da imagem')

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.