How to get all HREF and SRC values from a code

Asked

Viewed 1,346 times

2

Fala ae personal,

I need to get all the values href and src of the tags, link, a, img and script, so I developed the following code:

<html>

<script>


    $(document).ready(function() {

        function execute(){

            var conteudo = $('#insert').val();

            $('#processado').html(conteudo);

            var links = $('#processado a[href],#processado link[href],#processado script[src],#processado img[data-src]'); 
            $.each(links, function(index, item){
                var caminho =  $(item).attr('href') || $(item).attr('src') || $(item).attr('data-src') || 'Nothing';
                caminho = $(item).prop('tagName') + ":" + caminho;
                $.parseHTML($('#result').append(caminho + "<br>"));
            }); 
         }

        $('#execute').click(function(){
            execute();
        });
    });            


</script>      

<textarea id="insert" style="width:600px; height:80%;"></textarea>
<input id="execute" name="execute" type="submit" value="Execute">

<div id="processado" class="teste" style="display:none;">
</div>
<div id="result"><b>RESULTADO:</b><br>
</div>

Javascript works perfectly, however, when I copy a source code into the text-area and run the script, nothing happens.

Can someone help me with that?

From now on, very orbigado.

  • What a complicated path, huh. It’s not easier to set everything on one data-src in all and then filter through them?

5 answers

2

Here is another suggestion:

$(document).ready(function() {
  function execute() {
    var conteudo = $('#insert').val();
        var buffer = $('<div/>');

    buffer.html(conteudo);
        var urls = $('[href], [src]', buffer).map(function(index, item) {
      return this.href || this.src;
    }).get();
    $('#result').html(JSON.stringify(urls));
  }
  $('#execute').click(execute);
});

jsFiddle: http://jsfiddle.net/j2o1Lcz0/

I use a temporary div buffer import the contents of the textarea. I then search inside that div elements that have attribute src or href. Then using .map convert this element array into an array with its values, that is, its href and/or src. Use the .get() to convert jQuery object/array into a native array.

1

Hello,

I made a change to your code.

$(document).ready(function() {

    function execute(){

        var conteudo = $('#insert').val();

        $('#processado').html(conteudo);

        var links = $('#hideOutput').find('a[href],link[href], script[src],img[data-src]'); 

        $.each(links, function(index, item){
            var caminho =  $(item).attr('href') || $(item).attr('src') || $(item).attr('data-src') || 'Nothing';
            caminho = $(item).prop('tagName') + ":" + caminho;
            $.parseHTML($('#result').append(caminho + "<br>"));
        }); 
     }

    $('#execute').click(function(){
        execute();
    });
    });     

And in html

<textarea id="insert" style="width:600px; height:80%;"></textarea>
<input id="execute" name="execute" type="submit" value="Execute">

<div id="processado" class="teste" style="display:none;">
</div>
<div id="result"><b>RESULTADO:</b><br>
</div>

The change is to play the textarea content in a hidden div, so use the selectors to keep the . each, otherwise you will have to handle the string and this will get much more complex.

Example jsFiddler

See if it solves your problem.

0

thanks for the help, but I just ran my original code and it worked. What was giving problem is that in the code q I was trying to run there was the following line of code at the end.

    <script>
        ssiInit();
    </script>

After I removed that part, my script worked properly and brought me everything I needed.

The question that’s left now is, why did it hinder the execution of my script?

Hugs and thanks for all your help !!!

  • Did that function exist in your code? If not, I believe an error was generated (by trying to execute a non-existent function) and this "blocked" the execution of other scripts. If so, what she did?

  • This function existed in the code I was reading with my script....

0

I believe the simplest way to do this, is to take all the HTML directly in the post and send it to the attribute search process, see how I solved the problem:

HTML

<h2>
  Cole o HTML:
</h2>
<textarea id="insert" style="width:600px; height:300px;"></textarea><br>
  <input type="button"  onclick="executeScript()" value="Executar">

<div id="processado" class="teste" style="display:none;">
</div>

<div id="result"></div>

jQuery

 function executeScript() {
     var content = '<div>' + $('#insert').val() + '</div>';
     var data = '';
     $(content).find('[href],[src],[data-src]')
           .each(function (index, value) {
             data += ((value.src != undefined) ? value.src : (value.href != undefined) ?  value.href : (value.dataset.src != undefined) ? value.dataset.src : null !== null) +"<br>";
           });
           if ( data.indexOf('<br>') == -1 ) {
                 data = 'Não há links para serem processados!';
           }
           $('#result').html('<h3>RESULTADO:</h3>' + data);
 }

Here’s the working example

0

Follow a solution using Javascript only:

var rawHTML = document.getElementById("rawHTML");
var btGetLinks = document.getElementById("btGetLinks");
var listLinks = document.getElementById("listLinks");

btGetLinks.addEventListener("click", function () {
  listLinks.innerHTML = "";
  var template = document.createElement("template");
  template.innerHTML = rawHTML.value;

  var elements = template.content.querySelectorAll("[src], [href], [data-src]");      
  [].forEach.call(elements, function (element, indice) {    
    var item = document.createElement("li");
    var value = element.src || element.href || element.dataset.src || "";
    item.textContent = element.tagName + ": " + value;
    listLinks.appendChild(item);
  });
});
input, textarea, div {
  box-sizing: border-box;
}

#rawHTML {
  width: 100%;
  height: 240px;
}

ul {
  list-style-type:none
}
<div>
  <textarea id="rawHTML"></textarea>
</div>
<div>
  <input id="btGetLinks" type="button" value="Pegar Links" />
</div>
<div>
  <ul id="listLinks">

  </ul>
</div>

A small note, instead of assigning your arbitrary HTML to your temporary DIV, just create a fragment with HTML.

Another point, the a[href], link[href] and script[src] should point to a valid URL (not necessarily existing).

  • 2

    could point out the reason for the -1?

Browser other questions tagged

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